Reading a File in C Programming

Reading a File

To read a  file there are following  function available:

  1. Function fgetc():  Function fgetc() is used to read a single character at a time from the input file. The syntax of this function is −

            Syntax :

               int fgetc( FILE * fp );

  • Functions fgets():  Functions fgets() is used to reads string from input file, one line at a time. The syntax of this function is –

Syntax :

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

function fgets() copies the read string into the buffer buf and appending a null character to terminate the string.

Here “n” is a size of buffer.

*fp- is a file pointer.

If the function fgets() encounters a character ‘\n’  ( newline ) or the end of the file (            EOF ) before reading the maximum number of characters, then it will returns the characters read up to that point including the new line character.

  • Function fscan(): Function fscan() is also use to read strings from a file. The syntax of this function is –

Syntax :

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

 Note: fscan() function stops reading after encountering the first space character in file.

Closing a File

The fclose() function is used to close an already opened file.  The syntax of this function is −

 Syntax :

int   fclose( FILE *fp );

Function fclose(-) returns zero if the file is successfully closed, or EOF if there is an error in closing the file.

Example:  Write a C program to show the use of fgets() and fscan() function using file handling.

Suppose we have a file Book.txt, that have following content

Hello  hii  how are you I am aditya

OUTPUT

Description:  fscanf() function read only “Hello” because after that, it encountered a space. fscan() function stops reading after encountering the first space character in file.

Function fgets() reads the remaining line till it encountered end of line. fgets() is  reads string from input file, one line at a time.

Finally, the last fgets() reads the second line completely.

Example: Write a C program to open a file, read a file and close file using file handling.

                                                Or

Example:  Write a program to show the use of  fgetc() function.

Note:  Used for  reads a single character from file. It returns EOF at the end of file.

OUTPUT

The content of the file “file1” will be printed.