ichigo663
ichigo663

Reputation: 79

lseek cause segmentation file in O_APPEND mod

int main(int argc,char* argv[]){
    int fd;
    off_t foffset;
    char* fpath;
    char* rbuf;
    if(argc!=2){
        printf("insert filename as argument!\n");
        exit(1);
    }
    strcpy(fpath,argv[1]);
    if( (fd = open(fpath,O_RDWR | O_APPEND)) <0 )
        perror("error on open()");
    //try to use lseek in file opened in O_APPEND mode
    char buf[] = "I'm appending some text!\n"; 
    if( write(fd, buf , sizeof(buf)) <0 )
        perror("error on write()");
    printf("the write() operation was succesful, let's try to seek and read the file..\n");
    foffset = lseek(fd,0L,SEEK_CUR);
    if(foffset<0)
        perror("error on lseek() :");
    close(fd);
    return 0;
}

Why does it generate a segmentation fault when I execute this code?? The segFault occurs only if the lseek operation is added, otherwise is fine.

Upvotes: 0

Views: 463

Answers (2)

teppic
teppic

Reputation: 8195

If you want to use fpath separately, change your definition:

char fpath[30];

Now your strcpy will work as expected (though you should check the length of the string is under 30). You can just pass argv[1] directly, however, to open, since you're not doing anything else with it.

Upvotes: 0

Paul R
Paul R

Reputation: 212949

fpath is a wild pointer, i.e. you haven't allocated any storage for it before you call strcpy. However since you only need a const char * for the file name you can just make the following change.

Change:

strcpy(fpath,argv[1]);

to:

fpath = argv[1];

Upvotes: 2

Related Questions