Personal tools
You are here: Home cmgui Wiki tmpnam vs mkstemp
Views
FrontPage >> Peters notes >>

tmpnam vs mkstemp

last edited 1 year ago by pbier

The compiler gives a warning when compiling cmgui (and the perl_interpreter) that using tmpnam is bad and mkstemp should be used instead.

I have had a look at the code and there are three calls to tmpnam in cmgui. Two calls can be replaced with a call to mkstemp but I see no easy way to change the last call, as we are using tmpnam in an unusual way. Usually it is used to create a unique temporary file name just before an fopen call. In our case it is used to create a unique file name that becomes part of a command string which is then executed by calling the system function.

mkstemp is designed to create a unique temporary file name and open it in one go, protecting from the possibility of another routine replacing the filename with a symbolic link to a different file before it is opened. Because it also opens the file, it can not be used as a direct replacement for the last call to tmpnam.

Some useful links on the tmpnam vs mkstemp problem:

In general code like this:

  FILE *uid_file;
  char temp_uid_name[L_tmpnam];

  tmpnam(temp_uid_name)
  uid_file = fopen(temp_uid_name,"w");

Can be replaced with code like this:

  FILE *uid_file;
  char template_name[]="/tmp/cmguiXXXXXX";
  int temp_fd;

  temp_fd=mkstemp(template_name); 
  uid_file = fdopen(temp_fd,"w");

Note that in the above code I have not done any checking, to make it simpler to see how the calls work. You should check that tmpnam/fopen and mkstemp/fdopen succeed, using if statements. If they fail, return an error message.

Contributing to this site

Please add to the wiki any relevant information that you think might be useful to other users of this website. For example, you might like to contribute your experiences, questions and answers.

You are encouraged to contribute to this site regardless of your level of experience. Contributions are welcomed from new and regular visitors.

If you ask a question and receive an answer from a developer you should record it in the wiki. This information is extremely useful and can help other users overcome the same problem.

See how to add and edit pages for more information.