C++ Program to Create a Temporary File
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().
Syntax:
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");
exit(1);
}
// Writing in temporary file the content
fputs(write, fp);
rewind(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
fclose(fp);
return 0;
}
Output:
Welcome to Geeks For Geeks