C++ Program to Create a Temporary File
Last Updated :
31 Jul, 2022
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++
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
FILE * fp = tmpfile ();
char write[] = "Welcome to Geeks For Geeks" ;
if (fp == NULL)
{
perror ( "Error creating temporary file" );
exit (1);
}
fputs (write, fp);
rewind (fp);
char read[100];
fgets (read, sizeof (read), fp);
cout << read;
fclose (fp);
return 0;
}
|
Output:
Welcome to Geeks For Geeks
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...