开发者

Reading and writing using system calls

开发者 https://www.devze.com 2023-03-29 05:07 出处:网络
I have to use read a file and write the information to another file using system call. I have opened the file for reading as below

I have to use read a file and write the information to another file using system call. I have opened the file for reading as below

filedesc = open(argv[1],O_RDONLY); //which works fine opened a file to write as below: fdw=creat(strcat(store,argv[1]),PERMS) // PERMS 0666 Used lseek to reach to the one of file filedesc ( to reverse and print )

 #include<stdio.h>
 #include<fcntl.h>
 #include<sys/stat.h>
 #include<unistd.h>
 #include<sys/types.h>
 #include<string.h>

 int main(int argc, char *argv [ ])
  {

     int filedesc,n,i,fdw,pos;
     char c;
     const char * prefix = "reserve_";
     int needed = strlen( argv[ 1 ] ) + strlen( prefix ) + 1;
     char store[ needed ];
     strcp开发者_运维技巧y( store, prefix );

     if(argc != 2)
   {
       printf(" usage : %s filename ", argv[0]);
     }

         //strcat( store, argv[ 1 ] );
         //printf( "%s\n", store );


      filedesc =  open(argv[1],O_RDONLY);
         if(filedesc <1 )
            {  printf("Unable to open file\n");
          exit(1); }


     if((fdw=creat(strcat(store,argv[1]),PERMS))==-1)
      printf("Unable to create file,please use perror to find details\n");
    else printf("File created\n");



       if((pos=lseek(filedesc,0,SEEK_END))==0)
         {
           printf("Empty file\n");
            exit(-1);
           }
         i=pos-1; 
             //printf("%d",i);

            while(i!=0)
             {
             pos=lseek(filedesc,i-1,SEEK_SET);
              read(filedesc,&c,1);
              if( write(fdw,&c,1)!=1)  //information is not being written to the file
                printf("Error\n");     //pointed by fdw rather getting printed on the
                                       //screen
                i--;                     
            }

        close(filedesc);
          close(fdw);



            }

Problem: If i am running this without first argument, it gives a segmentation fault instead of the usage. Please help


Your if line is wrong. It will actually store the result of the comparison in fdw instead of storing the result of creat(2).

if(fdw=creat(strcat(store,argv[1]),PERMS)==-1) /* Wrong. */

Try:

if((fdw = creat(strcat(store, argv[1]), PERMS)) == -1)
   ^                                          ^

EDIT

You should also check the result of read:

if (read(filedesc, &c, 1) <= 0)
    break;
0

精彩评论

暂无评论...
验证码 换一张
取 消