C Program to Read a Line From a File and Display it
Example: Program to read text from a file
#include <stdlib.h> // For exit() function
if ((fptr = fopen("program.txt", "r")) == NULL)
printf("Error! opening file");
// Program exits if file pointer returns NULL.
// reads text until newline
printf("Data from the file:\n%s", c);
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.
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.