File Handling

Opening and Closing a File:

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

It creates a new file or to open an existing file and returns the pointer to the same. The returned pointer can be used for writing to the file or reading from the file.
Following are the access mode used for text files:

Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file.
a

r+

Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content.Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

For Binary Files following access modes must be used
“rb”, “wb”, “ab”, “rb+”, “r+b”, “wb+”, “w+b”, “ab+”, “a+b”
Closing a File:

int fclose( FILE *fp );

The fclose( ) function returns zero on success, or EOF if there is an error in closing the file
This function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file.
Writing and Reading in Text Format:
Writing to a Text File
To write individual characters to a stream

int fputc( int c, FILE *fp );

It returns the written character written on success otherwise EOF if there is an error
To write a null-terminated string to a stream:

int fputs( const char *s, FILE *fp );
int fprintf(FILE *fp, const char *format, …)

Both returs a non-negative value on success, otherwise EOF is returned in case of any error.

int fprintf(FILE *fp, const char *format, …)

Reading from a Text File
To read a single character from a file

int fgetc( FILE * fp );

The return value is the character read, or in case of any error it returns EOF
To Read a string from file

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n – 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.

Note: You can also use int fscanf(FILE *fp, const char *format, …) function to read strings from a file but it stops reading after the first space character encounters.