Reading a file line by line is a common task in C, useful for processing logs, configuration files, or any text data. This program opens a file in read mode using fopen(), checks for errors, then uses fgets() in a while loop to read one line at a time into a buffer. Each line is printed with its line number until end-of-file is reached. Finally, fclose() releases the file handle. The example demonstrates safe file handling, buffer management, and loop control — essential skills for real-world C file processing.
#include <stdio.h>
#include <stdlib.h>int main() {
FILE *file;
char line[256];
int lineNum = 1;file = fopen("input.txt", "r");
if (file == NULL) {
printf("Error: Could not open file. ");
return 1;
}while (fgets(line, sizeof(line), file) != NULL) {
printf("Line %d: %s", lineNum, line);
lineNum++;
}fclose(file);
return 0;
}
How It Works?
1.#include <stdio.h> / <stdlib.h> — Provides file I/O functions and NULL.
2.FILE *file; — Declares a file pointer to hold the file handle.
3.char line[256]; — Buffer to store one line at a time (adjust size as needed).
4.fopen("input.txt", "r"); — Opens the file in read mode; returns NULL on failure.
5.Error check — Prints a message and exits if the file can not be opened.
6.fgets(line, sizeof(line), file) — Reads up to sizeof(line) - 1 characters or until a newline; returns NULL at EOF, ending the loop.
7.printf — Prints each line with its line number.
8.fclose(file); — Closes the file to free resources.
Example
input.txt:
Hello World
C programming is fun
Reading files line by line
Output:
Line 1: Hello World
Line 2: C programming is fun
Line 3: Reading files line by line