File Assignment 21 — Print All Odd-Numbered Lines of a File First, Then All Even-Numbered Lines
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Print All Odd-Numbered Lines of a File First, Then All Even-Numbered Lines — Reading a File in Two Passes

📑 On this page:
  • How Odd and Even Line Printing Works
  • The Three Steps of the Program
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to open and read a text file using fopen() and fgets()
  • 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.

Diagram showing a C program reading a file twice to print odd-numbered lines first and even-numbered lines afterward

The Three Steps of the Program

Step File operation Effect
1. Read and print odd linesfgets() with an odd line counterLines 1, 3, 5, and so on are displayed first
2. Return to the beginningrewind(fp);The file pointer moves back to the first line
3. Read and print even linesfgets() with an even line counterLines 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 3 C, and line 5 E are printed.
  • rewind(fp) moves the file pointer back to line 1.
  • Second pass: line 2 B and line 4 D are 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.

📖 Related Tutorials

  • All File Handling Assignments in C
  • Count the Number of Lines in a File
  • Count the Number of Words in a File
  • Copy the Contents of One File to Another
  • Structure Assignments in C

Previous Topic: -->> File Assignments in C   ||   Next Topic: -->> File Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.