C examples for File:File Operation
To open a data file, use the standard input/output library function fopen().
#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().
Mode | Description |
---|---|
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.
#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"); }
You should close the file using a function called fclose().
fclose(pRead);