C Program to Read a Line From a File and Display it

This program reads text from a file and stores it in a string until enter ‘newline’ character is encountered.

Example: Program to read text from a file

  1. #include <stdio.h>
  2. #include <stdlib.h> // For exit() function
  3. int main()
  4. {
  5. char c[1000];
  6. FILE *fptr;
  7. if ((fptr = fopen("program.txt", "r")) == NULL)
  8. {
  9. printf("Error! opening file");
  10. // Program exits if file pointer returns NULL.
  11. exit(1);
  12. }
  13. // reads text until newline
  14. fscanf(fptr,"%[^\n]", c);
  15. printf("Data from the file:\n%s", c);
  16. fclose(fptr);
  17. return 0;
  18. }

If the file program.txt is not found, this program prints error message.

If the file is found, the program saves the content of the file to a string c until ‘\n’ newline is encountered.

Suppose, the program.txt file contains following text.

C programming is awesome.
I love C programming.
How are you doing?

The output of the program will be:

Data from the file: C programming is awesome.