sazr
sazr

Reputation: 25938

Many ways to create a Temporary file: what is the situation behind each method?

My C++ winAPI application has a need to create a temporary file prior to uploading the file to a server. So I have searched ways to create a temporary file & found there are many ways to do this.

Can you tell me: For each of the following methods below, in which scenario am I supposed to use that method? And which method would best suite my needs?

Method 1:

// Using CreateFile()
CreateFile( "myfile.txt", GENERIC_ALL, ..., FILE_ATTRIBUTE_TEMPORARY, 0); // removed unecessary parameters

Method 2:

// I think that GetTempFileName also creates the file doesn't it? Not just generates a unique fileName?
//  Gets the temp path env string (no guarantee it's a valid path).
dwRetVal = GetTempPath(MAX_PATH,          // length of the buffer
                       lpTempPathBuffer); // buffer for path 

//  Generates a temporary file name. 
uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files
                          TEXT("DEMO"),     // temp file name prefix 
                          0,                // create unique name 
                          szTempFileName);  // buffer for name 

Method 3:

// Create a file & use the flag DELETE_ON_CLOSE. So its a temporary file that will delete when the last HANDLE to it closes
HANDLE h_file = CreateFile( tmpfilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL ); 

Why are there more than 1 way to create a temp file. And, for example, what is the situation where I would want to use, say, method 2 over method 1?

Upvotes: 3

Views: 2838

Answers (2)

user2946737
user2946737

Reputation:

For method #2 if you use 0 for the "unique ID" you actually need to call SetFileAttributes with FILE_ATTRIBUTE_TEMPORARY to make the generated file temporary in the same sense as method #1 (otherwise it will be a normal ARCHIVE/NOT_CONTENT_INDEXED file.)

Use GetFileAttributes or GetFileInformationByHandle to see what attributes the file actually possesses.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308530

FILE_ATTRIBUTE_TEMPORARY simply tells Windows not to bother writing the file contents to disk if there's enough cache, because the file is temporary and no other process will be using it.

FILE_FLAG_DELETE_ON_CLOSE means just what it says - when you close the file it will be deleted automatically. This guarantees that it will be temporary.

GetTempFilename creates a name for a temporary file, and guarantees that the filename hasn't been used previously.

You should use all 3 methods when creating a temporary file. None of them interferes with the others.

Upvotes: 6

Related Questions