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:
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:
- 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:
#include <stdio.h>
void printOddEvenLines( char x[])
{
FILE * fp = fopen (x, "a+" );
if (!fp) {
printf ( "Unable to open/detect file" );
return ;
}
fprintf (fp, "\n" );
fseek (fp, 0, 0);
int check = 0;
char buf[100];
while ( fgets (buf, sizeof (buf), fp)) {
if (!(check % 2)) {
printf ( "%s" , buf);
}
check++;
}
check = 1;
fseek (fp, 0, 0);
while ( fgets (buf, sizeof (buf), fp)) {
if (!(check % 2)) {
printf ( "%s" , buf);
}
check++;
}
fclose (fp);
return ;
}
int main()
{
char x[] = "file1.txt" ;
printOddEvenLines(x);
return 0;
}
|
Input File:
Output File:
Last Updated :
08 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...