Reverse Content of File Using C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to reverse the content of a file using C programming language.
We will read the content of the input file character by character, and write it back in reverse order to the output file.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Open Input and Output Files

In the first step, we will open the input and output files using fopen() function. We will create two file pointers for these files, one for input and one for output.

FILE *input_file, *output_file;
input_file = fopen("input.txt", "r");
output_file = fopen("output.txt", "w");

Count the number of characters in the input file

In this step, we will count the number of characters in the input file using the fseek() and ftell() functions.
We will set the file position to the end of the file using fseek(input_file, 0, SEEK_END); and get the current file position using ftell(input_file);.
This will give us the total number of characters in the input file.

fseek(input_file, 0, SEEK_END);
long total_characters = ftell(input_file);

Copy the characters in reverse order from input file to output file

Now that we have the total number of characters in the input file, we will copy the characters in reverse order to the output file.
We will iterate through the input file character by character, and write each character to the output file using fputc() function.
We will start from the last character in the input file and move backwards using fseek(input_file, -1L, SEEK_CUR);.

for (long i = total_characters-1; i >= 0; i--) {
  fseek(input_file, i, SEEK_SET);
  char c = fgetc(input_file);
  fputc(c, output_file);
}

Close the input and output files

In the last step, we will close the input and output files using the fclose() function.

fclose(input_file);
fclose(output_file);

Summary

In this lab, we learned how to reverse the content of a file using C programming language. We opened the input and output files, counted the number of characters in the input file, copied the characters in reverse order to the output file, and closed the input and output files.

Other C Tutorials you may like