Question: Using only Unix system calls(like open, seek(), tell, etc.), write a C program to reverse the order of the lines in a text file. The
Using only Unix system calls(like open, seek(), tell, etc.), write a C program to reverse the order of the lines in a text file.
The first line becomes last, the second line becomes the one before the last one and so on.
Note: your program should have two arguments, the input file name and the output file name.
Call model: reverseFile
.
.
.
This is the code in standard I/O:
#include
#define MAX 100
int main(int argc, char *argv[]) { FILE *f1, *f2; if(argc!=3) { printf("Usage: reverseFile "); return 0; } //open the text files f1 = fopen(argv[1], "r"); f2 = fopen(argv[2], "w"); if(f1==NULL || f1==NULL) { printf("File not open!"); return 1; } long len[MAX]; char buf[MAX]; int i = 1, j; len[0] = 0; //store the starting position of each line while(!feof(f1)) { fgets(buf, MAX, f1); if(feof(f1)) break; len[i] = ftell(f1); i++; } //write to the text file for(j=i-2; j>=0; j--) { fseek(f1, len[j], 0); fgets(buf, MAX, f1); fputs(buf, f2); } //close the files fclose(f1); fclose(f2); return 0; }
I need it using Unix system calls only
any other answer will get down voted
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
