Nearby lessons

71 of 72

C - Reading from a File

Reading from a file allows a C program to use information saved earlier. Learn how to read a line with fgets() and how to stop when there is no more data to read.

1. Read a File Using fgets()

The fgets() function reads text from a file into a character array. It can read spaces and stops after a newline, when the buffer is full, or at the end of the file.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("message.txt", "r");
5 char line[100];
6 
7 if (fp == NULL) {
8 printf("Could not open the file\n");
9 return 1;
10 }
11 
12 while (fgets(line, sizeof line, fp) != NULL) {
13 printf("%s", line);
14 }
15 
16 fclose(fp);
17 return 0;
18}
Output
Displays each line stored in message.txt.

2. Read Formatted Data Using fscanf()

fscanf() is useful when the file contains data in a known format, such as a name followed by a number. The loop below continues while both values are read successfully.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("marks.txt", "r");
5 char name[30];
6 int marks;
7 
8 if (fp == NULL) {
9 printf("Could not open the file\n");
10 return 1;
11 }
12 
13 while (fscanf(fp, "%29s %d", name, &marks) == 2) {
14 printf("%s got %d marks\n", name, marks);
15 }
16 
17 fclose(fp);
18 return 0;
19}
Output
Rahul got 88 marks
Priya got 95 marks

3. Understanding EOF

EOF is a special value used by input functions to indicate that no more input can be read, or that an input error occurred. For beginners, prefer checking the return value of fgets() or the number of values returned by fscanf() instead of using feof() as the loop condition.

📝 Key Takeaways
  • Use r mode to read an existing file.
  • fgets() can read a line including spaces.
  • A loop using fgets() stops when no more line can be read.
  • Always close the file after reading.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3