- How to open and read a text file using
fopen()andfgets() - How to count line numbers while reading a file
- How to print odd-numbered lines first and even-numbered lines afterward
- How to move the file pointer back to the beginning using
rewind() - Why the file must be read twice for this output order
- How to close a file safely using
fclose()
How Odd and Even Line Printing Works
The program reads a text file and displays its lines in a special order: first all odd-numbered lines, then all even-numbered lines. For example, if the file contains five lines, the output order will be line 1, line 3, line 5, followed by line 2 and line 4.
A file can be read only once in a single forward pass using fgets(). Therefore, to print odd lines first and even lines afterward, the program reads the file twice. In the first pass, it prints lines at odd positions. Then it rewinds the file and reads it again to print lines at even positions.
The rewind() function moves the file position indicator back to the beginning of the file. This allows the same file pointer to be reused for the second reading pass without closing and reopening the file.
💡 In one line: Read the file once to print odd-numbered lines, use rewind() to return to the beginning, then read it again to print even-numbered lines.
The Three Steps of the Program
| Step | File operation | Effect |
|---|---|---|
| 1. Read and print odd lines | fgets() with an odd line counter | Lines 1, 3, 5, and so on are displayed first |
| 2. Return to the beginning | rewind(fp); | The file pointer moves back to the first line |
| 3. Read and print even lines | fgets() with an even line counter | Lines 2, 4, 6, and so on are displayed afterward |
The line counter starts from 1 because file lines are normally counted starting from the first line. A line number is odd when lineNumber % 2 != 0, and it is even when lineNumber % 2 == 0.
This approach avoids storing all lines in memory. Instead, the program reads the file twice, printing only the required lines during each pass. This is useful for large files where storing every line in an array may consume too much memory.
Complete C Program
Program: print all odd-numbered lines first, then all even-numbered lines
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 1000
int main(void) {
FILE *fp;
char filename[100];
char line[MAX_LINE];
int lineNumber;
printf("Enter the file name: ");
if (scanf("%99s", filename) != 1) {
printf("Invalid file name.\n");
return 1;
}
/* Open the file in read mode */
fp = fopen(filename, "r");
if (fp == NULL) {
printf("\nError: Unable to open file '%s'.\n", filename);
return 1;
}
printf("\nOdd-numbered lines:\n");
lineNumber = 1;
while (fgets(line, sizeof(line), fp) != NULL) {
if (lineNumber % 2 != 0) {
printf("%s", line);
}
lineNumber++;
}
/* Move the file pointer back to the beginning */
rewind(fp);
printf("\nEven-numbered lines:\n");
lineNumber = 1;
while (fgets(line, sizeof(line), fp) != NULL) {
if (lineNumber % 2 == 0) {
printf("%s", line);
}
lineNumber++;
}
fclose(fp);
return 0;
}
Program Output
Suppose the file sample.txt contains the following lines:
C is a powerful programming language.
File handling is an important topic.
fgets reads one line at a time.
rewind moves the file pointer backward.
fclose closes the file safely.
When the program is executed:
Enter the file name: sample.txt
Odd-numbered lines:
C is a powerful programming language.
fgets reads one line at a time.
fclose closes the file safely.
Even-numbered lines:
File handling is an important topic.
rewind moves the file pointer backward.
The program first prints lines 1, 3, and 5 because their line numbers are odd. After rewinding the file, it prints lines 2 and 4 because their line numbers are even.
Step-by-Step Explanation
Let us understand how the program reads the file and prints the required lines.
1. Opening the file
fopen(filename, "r") opens the file in read mode. If the file does not exist or cannot be opened, fopen() returns NULL. The program checks this condition and displays an error message.
2. Reading lines with fgets
fgets(line, sizeof(line), fp) reads one line at a time from the file into the line array. It stops when it reads a newline character, reaches the buffer limit, or reaches the end of the file.
3. Counting line numbers
The variable lineNumber starts at 1 and increases after every successful fgets() call. This allows the program to identify whether the current line is odd or even.
4. Printing odd-numbered lines
During the first pass, the condition lineNumber % 2 != 0 is true for lines 1, 3, 5, and so on. Therefore, only odd-numbered lines are printed.
5. Rewinding the file
After the first pass, the file pointer is at the end of the file. The statement rewind(fp); moves it back to the beginning so the file can be read again.
6. Printing even-numbered lines
During the second pass, the line counter again starts from 1. The condition lineNumber % 2 == 0 is true for lines 2, 4, 6, and so on. Therefore, only even-numbered lines are printed.
7. Closing the file
fclose(fp) closes the file and releases the resources associated with it. Every file opened with fopen() should be closed after its use.
8. Example trace
For a file with the lines A, B, C, D, and E:
- First pass: line 1
A, line 3C, and line 5Eare printed. rewind(fp)moves the file pointer back to line 1.- Second pass: line 2
Band line 4Dare printed. - Final output order:
A,C,E,B,D.
9. Why two passes are needed
A single forward pass through a file cannot print odd lines first and then even lines, because once the program moves beyond a line, it cannot return to it without rewinding. Reading the file twice keeps the solution simple and memory-efficient.
10. Complexity summary
If the file contains n lines, the program reads the file twice, so its time complexity is O(n). Space complexity is O(1) because only one line buffer is used at a time; the program does not store the entire file in memory.
🎯 Remember this: Use fgets() to read one line at a time, count each line, print odd-numbered lines in the first pass, call rewind(fp), and print even-numbered lines in the second pass.
Frequently Asked Questions
1. Why is rewind() used in this program?
After the first reading pass, the file pointer reaches the end of the file. rewind() moves it back to the beginning so the program can read the file again and print the even-numbered lines.
2. Can this program be written using only one pass?
Not easily if memory usage must remain low. A single-pass solution would need to store all lines in memory first, then print odd and even lines separately. Reading the file twice avoids that extra memory usage.
3. What does fgets() return at the end of a file?
fgets() returns NULL when it reaches the end of the file or an error occurs. The while loop uses this return value to stop reading.
4. Does fgets() include the newline character?
Yes. If a newline character is present before the buffer limit, fgets() stores it in the string. This is why the program can print each line with its original formatting.
5. What happens if the file does not exist?
fopen() returns NULL. The program checks this value and prints an error message instead of trying to read from an invalid file pointer.
6. What is the time complexity of this program?
The time complexity is O(n), where n is the number of lines in the file. The file is read twice, but each line is processed a constant number of times. Space complexity is O(1) because only one line buffer is used.
💡 Tip: After implementing this program, try modifying it to print even-numbered lines first and odd-numbered lines afterward. You only need to reverse the order of the two reading passes.