C program to reverse the content of the file and print it
Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.
Examples:
Input:
file1.txt has:
Welcome
to
GeeksforGeeks
Output:
GeeksforGeeks
to
Welcome
GeeksforGeeks
Input:
file1.txt has:
This is line one
This is line two
This is line three
This is line four
This is line five
Output:
This is line five
This is line four
This is line three
This is line two
This is line one
Approach:
- Initialise previous length of the text as 0.
- Find the length of the current line and add it to the previous length. This given the next starting index of the new line.
- Repeat the above steps till the end of the file.
- Initialise the array of length of the given message in the given file.
- Now rewind your file pointer and place the last pointer of the text to arr[K – 1] where K is the length of the array using fseek().
- Print the length of the last line and decrease K by 1 for printing the next last line of the file.
- Repeat the above steps until K is equals to 0.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
#define MAX 100
void reverseContent( char * x)
{
FILE * fp = fopen (x, "a+");
if (fp == NULL) {
printf ("Unable to open file\n");
return ;
}
char buf[100];
int a[MAX], s = 0, c = 0, l;
fprintf (fp, " \n");
rewind (fp);
while (! feof (fp)) {
fgets (buf, sizeof (buf), fp);
l = strlen (buf);
a = s += l;
}
rewind (fp);
c -= 1;
while (c >= 0) {
fseek (fp, a, 0);
fgets (buf, sizeof (buf), fp);
printf ("%s", buf);
c--;
}
return ;
}
int main()
{
char x[] = "file1.txt";
reverseContent(x);
return 0;
}
|
Input File:
Output File:
Last Updated :
17 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...