13.20. tmpfile()

Create a temporary file


#include <stdio.h>

FILE *tmpfile(void);


This is a nifty little function that will create and open a temporary file for you, and will return a FILE* to it that you can use. The file is opened with mode "r+b", so it's suitable for reading, writing, and binary data.

By using a little magic, the temp file is automatically deleted when it is close()'d or when your program exits. (Specifically, tmpfile() unlinks the file right after it opens it. If you don't know what that means, it won't affect your tmpfile() skill, but hey, be curious! It's for your own good!)

Return Value

This function returns an open FILE* on success, or NULL on failure.


#include <stdio.h>

int main(void)
    FILE *temp;
    char s[128];

    temp = tmpfile();

    fprintf(temp, "What is the frequency, Alexander?\n");

    rewind(temp); // back to the beginning

    fscanf(temp, "%s", s); // read it back out

    fclose(temp); // close (and magically delete)

    return 0;

See Also