Course contentsShow
← C
Lesson 759 of 1,21910. Input and OutputFree lesson

Generating temp filenames with tmpnam

Generating temp filenames with tmpnam

What you'll learn: How to use the tmpnam function to generate a unique, non-conflicting filename for temporary data storage.

When writing programs, you sometimes need a "scratchpad"—a place to store data temporarily while the program is running, only to discard it when the work is finished. Imagine you are organizing a massive library. You don't want to shove every unsorted book into the main archive immediately. Instead, you grab a blank cardboard box, scribble a unique ID on it, and use it to hold books while you sort them.

In C, the tmpnam function (found in <stdio.h>) is the tool that generates that unique "ID" for your temporary file.

How tmpnam Works

The tmpnam function doesn't actually create a file; it just brainstorms a name that is guaranteed not to belong to any existing file at that exact moment. It ensures that if you decide to create a file with that name, you won't accidentally overwrite your user's important documents.

Here is how you use it in code:

#include <stdio.h>

int main() {
    // L_tmpnam is a constant defining the required buffer size
    char filename[L_tmpnam];

    // Generate the unique name and store it in our buffer
    if (tmpnam(filename) != NULL) {
        printf("Temporary filename generated: %s\n", filename);
        
        // You can now use this name with fopen
        FILE *tempFile = fopen(filename, "w");
        if (tempFile) {
            fprintf(tempFile, "This is temporary data.");
            fclose(tempFile);
            
            // Clean up: Remember to delete it when done!
            remove(filename);
        }
    } else {
        printf("Failed to generate a unique name.\n");
    }

    return 0;
}

Safety and Best Practices

When you call tmpnam(filename), the function fills your character array with a string like /tmp/fileA3bZ.

However, there is a catch. Because tmpnam only gives you a name and doesn't lock the file, there is a tiny window of time between getting the name and calling fopen where another program could theoretically grab that same name. This is known as a "race condition."

In modern, high-security professional software, developers often use more advanced functions like mkstemp. But for learning the basics of system-level I/O, tmpnam is the classic way to understand how programs request "scratch space" from the operating system. Just remember: if you create it, you are responsible for deleting it with remove() before your program exits!

Key takeaway

tmpnam generates a unique string that can safely be used as a filename for temporary storage without overwriting existing files.