Trusted answers to developer questions

fopen() in C++

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 ©2024 Educative, Inc. All rights reserved
Did you find this helpful?