Create temporary file in C, MS Windows system

Istrebitel picture Istrebitel · Mar 15, 2012 · Viewed 6.9k times · Source

Basically, i have a program that is given a 4 meg compressed file, it has to decode this file into uncompressed ~ 100 meg, then compress it back into ~4 meg file. I need to store this intermediate 100 meg file somewhere on the drive (dont want to keep it in memory).

Program is written in C and will be executed on MS Windows 7. At the moment of uncompressing, no guaranteed folder (with write access) is given to the program (folder with source file might be read only and folder with target file might be not yet specified).

This has proven to be not an easy task:

1) I have read about a C function that creates a temp file that will disappear when closed or program is terminated. However, from what i understand it tries to make the file on disk C, in root directory, so this will obviously fail if user has no rights for that (which normal user doesnt)

2) I had an idea to use environmental/system variable TEMP and create a file there, BUT looking on a random Win7 PC which wasnt tweaked, i see that this variable points to c:/windows/temp, and that folder has specific rights for "users" - that is, they have rights to read, execute, create and write files, but not to delete them, check their attributes, etc. This means, i assume, that if program is ran with user privilleges, it will be able to make a file but not able to delete it, so the only way to "delete" it would be to open the file for writing and then close it, making it a 0 length file. This is also not desired, and i dont know how to query for system variables from C

3) So, basically, only idea i have right now is to make a function to open file that:

  • tries to create a temp file in the output dir, if possible
  • if failed, tries to create a temp file in input dir
  • if failed, tries to create a temp file in TEMP dir from system variable
  • if failed, tries to create a temp file in TMP dir from system variable

and a delete function that:

  • tries to remove() the file (by its name that is stored somewhere)
  • if failed, it tries to open the file for write, and close it, so it becomes a 0 byte file

Are there better ideas?

Any help is appreciated, thanks!

PS: Program must not use any external libraries like MFC or something, only built-in standart C functions

Answer

Roman R. picture Roman R. · Mar 15, 2012

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.