C++ fopen()

fopen() prototype

FILE* fopen (const char* filename, const char* mode);

The fopen() function takes a two arguments and returns a file stream associated with that file specified by the argument filename.

It is defined in <cstdio> header file.

Different types of file access mode are as follows:

File Access Mode Interpretation If file exists If file doesn't exist
"r" Opens the file in read mode Read from start Error
"w" Opens the file in write mode Erase all the contents Create new file
"a" Opens the file in append mode Start writing from the end Create new file
"r+" Opens the file in read and write mode Read from start Error
"w+" Opens the file in read and write mode Erase all the contents Create new file
"a+" Opens the file in read and write mode Start writing from the end Create new file

fopen() Parameters

  • filename: Pointer to the string containing the name of the file to be opened.
  • mode: Pointer to the string that specifies the mode in which file is opened.

fopen() Return value

  • If successful, the fopen() function returns a pointer to the FILE object that controls the opened file stream.
  • On failure, it returns a null pointer.

Example 1: Opening a file in write mode using fopen()

#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
	int c;
	FILE *fp;
	fp = fopen("file.txt", "w");
	char str[20] = "Hello World!";
	if (fp)
	{
		for(int i=0; i<strlen(str); i++) 
			putc(str[i],fp);
	}
	fclose(fp);
}

When you run the program, it will not generate any output but will write "Hello World!" to the file "file.txt".

Example 2: Opening a file in read mode using fopen()

#include <cstdio>

using namespace std;

int main()
{
	int c;
	FILE *fp;
	fp = fopen("file.txt", "r");
	if (fp)
	{
		while ((c = getc(fp)) != EOF)
			putchar(c);
		fclose(fp);
	}
	return 0;
}

When you run the program, the output will be [Assuming the same file as in Example 1]:

Hello World!

Example 3: Opening a file in append mode using fopen()

#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
	int c;
	FILE *fp;
	fp = fopen("file.txt", "a");
	char str[20] = "Hello Again.";
	if (fp)
	{
		putc('\n',fp);
		for(int i=0; i<strlen(str); i++) 
			putc(str[i],fp);
	}
	fclose(fp);
}

When you run the program, it will not generate any output but will append "Hello Again" in a newline to the file "file.txt".


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges