Skip to content
Related Articles

Related Articles

C program to print odd line contents of a File followed by even line content
  • Difficulty Level : Medium
  • Last Updated : 08 Jul, 2020

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:
to

Input: 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:

  1. Open the file in a+ mode.
  2. Insert a new line at the end of the file, so that the output doesn’t get effected.
  3. Print odd lines of the file by keeping a check, that doesn’t print even lines of the file.
  4. Rewind the file pointer.
  5. Reinitialize check.
  6. 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program for the above approach
  
#include <stdio.h>
  
// Function which prints the file content
// in Odd Even manner
void 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 Code
int main()
{
    // Input filename
    char x[] = "file1.txt";
  
    // Function Call
    printOddEvenLines(x);
  
    return 0;
}

chevron_right


Input File:

Output File:

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :