Tuesday, July 12, 2011

Read the contents of a file and store it in reverse order

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
int main(){
   int fd,fd2,count=-1;
   char buffer,dest[30],source[30],flag='y';
   printf("\nEnter the source file name:- ");
   gets(source);
   fd = open(source,O_RDWR);
   if(fd!=-1){
       printf("\nEnter the destination file name:- ");
       gets(dest);
       fd2 = open(dest,O_RDWR);
       if(fd2!=-1){
          printf("\nDestination file already present. Enter 'y' to overwrite ");
          flag=getchar();
      }
      if(flag=='y'){
         fd2 = creat(dest,O_RDWR|0666);
         while(lseek(fd,count,2)!=-1){
             count--;
             read(fd,&buffer,sizeof(char));
             write(fd2,&buffer,sizeof(char));
         }
      }
   }
   else
       printf("\nSource file not found");
   close(fd);
   return 0;
}

No comments:

Post a Comment