X

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

In this example, you will learn to read text from a file and store it in a string until the newline ‘\n’ character is encountered.

Limited time offer: Get 10 free Adobe Stock images.ADS VIA CARBON

To understand this example, you should have the knowledge of the following C programming topics:


Program to read text from a file

#include #include // For exit() function int main() { char c[1000]; FILE *fptr; if ((fptr = fopen("program.txt", "r")) == NULL) { printf("Error! opening file"); // Program exits if file pointer returns NULL. exit(1); } // reads text until newline is encountered fscanf(fptr, "%[^\n]", c); printf("Data from the file:\n%s", c); fclose(fptr); return 0; }

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 the following text in the current directory.

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.

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

Categories: Uncategorized
ilexjjtt-ca: