C++ tmpfile()

The file will be automatically deleted when it is closed by the program(by executing fclose) or when the program terminates.

tmpfile() prototype

FILE* tmpfile();

It is defined in <cstdio> header file.

tmpfile() Parameters

None

tmpfile() Return value

  • If successful, it returns a stream pointer to the temporary file created.
  • On failure, it returns null.

Example: How tmpfile() function works

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

int main()
{
	FILE *fp;
	fp = tmpfile();
	char writeToFile[50] = "Creating a temporary file";
	
	if (fp==NULL)
	{
		perror("Error creating temporary file");
		exit(1);
	}
	
	fputs(writeToFile,fp);
	rewind(fp);
	
	char readFromFile[50];
	fgets(readFromFile, sizeof(readFromFile), fp);
	cout << readFromFile;
	fclose(fp);
	
	return 0;
}

When you run the program, the output will be:

Creating a temporary file
Did you find this article helpful?