Component of the Week #9: bdls_tempdirectoryguard

Summary:
  • Provides a mechanism to create and remove temporary directories.

When writing unit tests, it is common to create temporary files and directories that are used only during the test.

The bdls_tempdirectoryguard component provides an RAII guard that creates a temporary directory in the constructor and removes it (recursively) when the guard is destroyed. The temporary directory is created in the system’s temporary directory or in the current working directory if the system’s temporary directory is not available.

As this class is primarily intended for testing, any failures to build the directory name or create the temporary directory will be fatal.

#include <bdls_tempdirectoryguard.h>
#include <bdls_filesystemutil.h>
#include <bdls_pathutil.h>

#include <bsl_iostream.h>

void foo_test()
{
    bsl::string tempDir;
    {
        bdls::TempDirectoryGuard guard("foo_test_");

        tempDir = guard.getTempDirName();

        // Create a file in the temporary directory
        bsl::string fileName = guard.getTempDirName();
        bdls::PathUtil::appendRaw(&fileName,"testfile.dat");

        bdls::FilesystemUtil::FileDescriptor fd =
            bdls::FilesystemUtil::open(fileName,
                                       bdls::FilesystemUtil::e_OPEN_OR_CREATE,
                                       bdls::FilesystemUtil::e_READ_WRITE);

        if (fd == bdls::FilesystemUtil::k_INVALID_FD) {
            bsl::cerr << "Failed to create file: " << fileName << "\n";
            return;
        }

        bdls::FilesystemUtil::close(fd);

        if (bdls::FilesystemUtil::exists(tempDir)) {
            bsl::cout << "Temp directory: " << tempDir << " exists (in scope)!\n";
        }

        if (bdls::FilesystemUtil::exists(fileName)) {
            bsl::cout << "Test file: " << fileName << " exists!\n";
        }
    }

    if (!bdls::FilesystemUtil::exists(tempDir)) {
        bsl::cout << "Temp directory: " << tempDir
                  << " does not exist (out of scope)!\n";
    }
}

int main() {
    foo_test();
    return 0;
}
Check out the full documentation for

Happy coding!