C program to print odd line contents of a File followed by even line content
Pre-requisite: Basics of File Handling in C
Given a text file in a directory, the task is to print all the odd line content of the file first then print all the even line content.
Examples:
Input: file1.txt:
Welcome
to
GeeksforGeeks
Output:
Odd line contents:
Welcome
GeeksforGeeks
Even line contents:
toInput: file1.txt:
1. This is Line1.
2. This is Line2.
3. This is Line3.
4. This is Line4.Output:
Odd line contents:
1. This is Line1.
3. This is Line3.
Even line contents:
2. This is Line2.
4. This is Line4.
Approach:
- Open the file in a+ mode.
- Insert a new line at the end of the file, so that the output doesn’t get effected.
- Print odd lines of the file by keeping a check, that doesn’t print even lines of the file.
- Rewind the file pointer.
- Reinitialize check.
- Print even lines of the file by keeping a check, that doesn’t print odd lines of the file.
Below is the implementation of the above approach:
// C program for the above approach #include <stdio.h> // Function which prints the file content// in Odd Even mannervoid printOddEvenLines(char x[]){ // Opening the path entered by user FILE* fp = fopen(x, "a+"); // If file is null, then return if (!fp) { printf("Unable to open/detect file"); return; } // Insert a new line at the end so // that output doesn't get effected fprintf(fp, "\n"); // fseek() function to move the // file pointer to 0th position fseek(fp, 0, 0); int check = 0; char buf[100]; // Print Odd lines to stdout while (fgets(buf, sizeof(buf), fp)) { // If check is Odd, then it is // odd line if (!(check % 2)) { printf("%s", buf); } check++; } check = 1; // fseek() function to rewind the // file pointer to 0th position fseek(fp, 0, 0); // Print Even lines to stdout while (fgets(buf, sizeof(buf), fp)) { if (!(check % 2)) { printf("%s", buf); } check++; } // Close the file fclose(fp); return;} // Driver Codeint main(){ // Input filename char x[] = "file1.txt"; // Function Call printOddEvenLines(x); return 0;} |



