Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

fopen()
c++
file handling

fopen() in C++

Educative Answers Team

In the world of computer science, file handling is a very important concept. A file is a type of portable storage that is used to store any type of data. Before a programmer applies any algorithm on a particular file, they need to open that file using the fopen() command.

Syntax

fopen() only has 2 parameters passed into it:

  • name of the file
  • file permissions
FILE *filePointer;
filePointer = fopen("filename.txt", "w");

File permissions

  • r = Reads files, but only if they exist.
  • w = Creates files and writes in them.
  • r+ = Reads files for input and output (only if they exist).
  • w+ = Creates files and opens them for both input and output.

Code

The following code opens a file and writes “Educative!” in it.

#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
	int c;
	FILE *filePointer;
	filePointer = fopen("filename.txt", "w");
	char sampleString[20] = "Educative!";
	if (filePointer)
	{
		for(int i=0; i<strlen(sampleString); i++) 
			putc(sampleString[i],filePointer);
	}
	fclose(filePointer);
}

RELATED TAGS

fopen()
c++
file handling
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring