How to print odd line contents of a file followed by even line content in C

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:

 
// C program for the above approach

#include 

// 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;
}

 

Submit Your Programming Assignment Details