Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ Program to Create a Temporary File

Improve Article
Save Article
  • Last Updated : 31 Jul, 2022
Improve Article
Save Article

Here, we will see how to create a temporary file using a C++ program. Temporary file in C++ can be created using the tmpfile() method defined in the <cstdio> header file. The temporary file created has a unique auto-generated filename. The file created is opened in binary mode and has access mode “wb+”. These temporary files are automatically deleted when the program is terminated or when they are closed in the program using fclose().


std::FILE* tmpfile();

Return value: The associated file stream or a null pointer if an error has occurred.

Below is the C++ program to create a temporary file, writing in and reading from the temporary file:


// C++ program to create a temporary file
// read and write to a temporary file.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
// Driver code
int main()
    // Creating a file pointer which
    // points to the temporary file
    // created by tmpfile() method
    FILE* fp = tmpfile();
    // Content to be written in temporary file
    char write[] = "Welcome to Geeks For Geeks";
    // If file pointer is NULL there is
    // error in creating the file
    if (fp == NULL)
        perror("Error creating temporary file");
    // Writing in temporary file the content
    fputs(write, fp);
    // Reading content from temporary file
    // and displaying it
    char read[100];
    fgets(read, sizeof(read), fp);
    cout << read;
    // Closing the file. Temporary file will
    // also be deleted here
    return 0;


Welcome to Geeks For Geeks
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!