How to Create a Temporary Directory in C++

create a unique temporary directory

Your code is fine. Because you try to create the directory the OS will arbitrate between your process and another process trying to create the same file so, if you win, you own the file and if you lose you get an error.

I wrote a similar function recently. Whether you throw an exception or not depends on how you want to use this function. You could, for example simply return either an open or closed std::fstream and use std::fstream::is_open as a measure of success or return an empty pathname on failure.

Looking up std::filesystem::create_directories it will throw its own exception if you don't supply a std::error_code parameter so you don't need to throw your own exception:

std::filesystem::path tmp_dir_path {std::filesystem::temp_directory_path() /= std::tmpnam(nullptr)};

// Attempt to create the directory.
std::filesystem::create_directories(tmp_dir_path));

// If that failed an exception will have been thrown
// so no need to check or throw your own

// Directory successfully created.
return tmp_dir_path;

Creating a unique temporary directory from pure C in windows

You can use what GetTempPath returns concatenated with a Guid to ensure uniqueness of the directory. You can create a Guid using UuidCreate or CoCreateGuid Function.

To delete recursively the directory, there is an example here in pure C: How to remove directory recursively? based on FindFirstFile, FindNextFile, DeleteFile and RemoveDirectory.

There is also SHFileOperation but it's more heavyweight and is based on the Windows Shell functions, and the Shell DLLs are not always wanted, especially if you're writing server code.

Where to create a temporary file from within a test

Thanks everybody, I found the problem.

Turns-out that in case the file doesn't exist and should be created - it seems that I must specify the mode, and use the 3-parameter version of open.

m_hFile = open("/tmp/mytest.bin", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);

Create temporary file in C, MS Windows system

GetTempPath

Retrieves the path of the directory designated for temporary files.

GetTempFileName

Creates a name for a temporary file. If a unique file name is
generated, an empty file is created and the handle to it is released;
otherwise, only a file name is generated.

These two provide you easy way to obtain a location and name for a temporary file.

UPD: Code sample on MSDN: Creating and Using a Temporary File.

How to create temporary folder in local system using c#

This will create a temporary directory:

   string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);


Related Topics



Leave a reply



Submit