File Pointer and open file function - C File

C examples for File:File Operation

Introduction

A file pointer is a pointer to a structure of type FILE.

To obtain a file pointer variable, use a statement like this:

FILE *fp;

Opening a File

The fopen( ) function opens a stream for use and links a file with that stream. The fopen( ) function has this prototype,

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

The following code uses fopen( ) to open a file named TEST for output.

FILE  *fp;
fp = fopen("test",  "w");

File open mode

ModeMeaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or create a text file for read/write
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append or create a binary file for read/write

The following pattern of code is used for opening a file.

FILE *fp;
 
if ((fp = fopen("test","w"))==NULL) {
  printf("Cannot open file.\n");
  exit(1);
}

Related Tutorials