C++ fclose()

The fclose() function in C++ closes the given file stream.

fclose() prototype

int fclose(FILE* stream);

The fclose() function takes a single argument, a file stream which is to be closed. All the data that are buffered but not written are flushed to the OS and all unread buffered data are discarded.

Even if the operation fails, the stream is no longer associated with the file. If the file pointer is used after fclose() is executed, the behaviour is undefined.

It is defined in <cstdio> header file.

fclose() Parameters

stream: The file stream to close.

fclose() Return value

The fclose() function returns:

  • Zero on success.
  • EOF on failure.

Example: How fclose() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
	FILE *fp;
	fp = fopen("file.txt","w");
	char str[20] = "Hello World!";
	
	if (fp == NULL)
	{
		cout << "Error opening file";
		exit(1);
	}
	fprintf(fp,"%s",str);
	fclose(fp);
	cout << "File closed successfully";
	return 0;
}

When you run the program, the output will be:

File closed successfully