C++ provides the tmpfile() function to create a temporary file for storing data during program execution. The file is opened in binary update mode and is automatically removed when it is closed or the program terminates.
- tmpfile() is defined in the <cstdio> header and returns a FILE*.
- The temporary file has an implementation-defined unique name and is automatically deleted when closed.
Example:
Input: No input is required.
Output: Welcome to Geeks For Geeks
Approach to Create a Temporary File
The temporary file can be created using tmpfile(), after which data can be written to and read from the file.
- Call tmpfile() to create and open a temporary file.
- Check whether the returned file pointer is NULL.
- Write data to the file using fputs().
- Move the file position back to the beginning using rewind().
- Read the data using fgets().
- Close the file using fclose(), which also removes the temporary file.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
// Create a temporary file
FILE* fp = tmpfile();
// Check if the file was created successfully
if (fp == NULL)
{
perror("Error creating temporary file");
return 1;
}
// Write data to the temporary file
const char* text = "Welcome to Geeks For Geeks";
fputs(text, fp);
// Move the file pointer to the beginning
rewind(fp);
// Read data from the temporary file
char buffer[100];
fgets(buffer, sizeof(buffer), fp);
cout << buffer;
// Close and remove the temporary file
fclose(fp);
return 0;
}
Output
Welcome to Geeks For Geeks
Explanation: tmpfile() creates and opens a temporary file and returns a FILE* pointing to it. The program writes data using fputs(), reads it after resetting the file position with rewind(), and closes the file using fclose().