fopen() in C++

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);
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved