Program: Printing the Contents of a File in Reverse Order

Problem Statement

Write a C program that reads the contents of a file and prints them in reverse order. The program should open the file, read its contents, and then print the characters or lines in reverse order.

Algorithm

  1. Open the File for Reading

    • Use the fopen function to open the file in read mode.

    FILE *filePointer;
    filePointer = fopen("input.txt", "r");
    • Check if the file is successfully opened.

    if (filePointer == NULL) {
        // Handle file opening error
    }
  2. Find the Size of the File

    • Use fseek and ftell to find the size of the file.

    fseek(filePointer, 0, SEEK_END); // Move to the end of the file
    long fileSize = ftell(filePointer); // Get the size of the file
    fseek(filePointer, 0, SEEK_SET); // Move back to the beginning
  3. Read and Print the Contents in Reverse

    • Use a loop to read characters or lines in reverse order and print them.

    char character;
    for (long i = fileSize - 1; i >= 0; i--) {
        fseek(filePointer, i, SEEK_SET);
        character = fgetc(filePointer);
        printf("%c", character);
    }
    • Alternatively, if the file contains lines, read and print them in reverse order.

    char line[100]; // Adjust the size based on the maximum line length
    fseek(filePointer, 0, SEEK_END);
    long currentPosition = ftell(filePointer);
    
    while (currentPosition > 0) {
        fseek(filePointer, currentPosition - 1, SEEK_SET);
        character = fgetc(filePointer);
    
        if (character == '\n') {
            // Print the line
            printf("%s\n", line);
            // Reset the line buffer
            memset(line, 0, sizeof(line));
        } else {
            // Concatenate the character to the line buffer
            strncat(line, &character, 1);
        }
    
        currentPosition--;
    }
  4. Close the File

    • Close the file after reading and printing.

    fclose(filePointer);

Explanation

This program reads the contents of a file and prints them in reverse order. The size of the file is determined, and then characters or lines are read in reverse order using fseek and fgetc. Finally, the file is closed.

Ensure that the input file exists and has the necessary permissions for reading. This program provides a simple way to print the contents of a file in reverse order.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!