Opening and Closing Files - C File

C examples for File:File Operation

Introduction

To open a data file, use the standard input/output library function fopen().

Demo Code

#include <stdio.h> 
int main()/*w  ww  .j  a v  a2 s  . c om*/
{ 
   FILE *pRead; 
   pRead = fopen("file1.dat", "r"); 
} 

The following table lists a few common options for opening text files using fopen().

ModeDescription
r Opens file for reading
w Creates file for writing; discards any previous data
a Writes to end of file (append)

To test fopen()'s return value, test for a NULL value in a condition.

Demo Code

#include <stdio.h> 
int main()//from   w  w w.jav a  2  s  .  c o  m
{ 
   FILE *pRead; 
   pRead = fopen("file1.dat", "r"); 
   if ( pRead == NULL ) 
      printf("\nFile cannot be opened\n"); 
   else 
      printf("\nFile opened for reading\n"); 
} 

Result

You should close the file using a function called fclose().

fclose(pRead);

Related Tutorials