Copy contents of a file in reverse order using lseek()

The following is a C code for copying the contents of one file in reverse order in another file. It is fairly easy, once you understand how lseek works.

#include <stdio.h>
#include <stdlib.h>
#include<fcntl.h>

char buffer[1];

int main()
{
int fd1,fd2;     //the two file descriptors
char file1[50],file2[50];
printf(“Enter file to reverse: “);
gets(file1);   //Input path of first file
if((fd1=open(file1,O_RDONLY))==-1)  //open will return -1 if there is an error
{
printf(“File does not exist\n”);
return -1;
}
printf(“Enter file to output in: “);
gets(file2);   //Input path of second file
fd2=open(file2,O_RDWR | O_CREAT,0777);   // will open file in read-write mode or create it if it does not exist
int size=lseek(fd1,0,SEEK_END);   //to find the size of the file
printf(“%d”,size);
int i;
for(i=1;i<=size;i++)
{
if((lseek(fd1,-i,SEEK_END))==-1)   //will point to position -i from the end of the file fd1
{
printf(“%s\n”,strerror(errno));
}
int rd=read(fd1,buffer,1);    //read one char at a time from file1 (use fd1)
int wr=write(fd2,buffer,1);  //write one char at a time to file2 (use fd2)
if(wr==0)
{
printf(“Did not write to file\n”);
return -1;
}
}
return 0;
}

Disclaimer: This code is inefficient and is meant for homework assignments and lab excercises. It cannot be used in real world problem since reading and writing chars one at a time is a wasteful approach.

Leave a comment