English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to read text from a file and store it in a string until a newline character '\n' is encountered.
To understand this example, you should be familiar with the followingC language programmingTopic:
#include <stdio.h> #include <stdlib.h> // For exit() function int main() { char c[1000]; FILE *fptr; if ((fptr = fopen("program.txt", "r")) == NULL) { printf("Error! opening file"); //If the file pointer returns NULL, the program exits. exit(1); } // Read the text until a newline character 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 file content as a string c until a newline character '\n' is encountered.
Assuming the program.txt file is in the current directory and contains the following text.
C programming is awesome. I love C programming. How are you doing?
The output of this program will be:
Data from the file: C programming is awesome.
If program.txt cannot find the file, the program will display an error message.