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;
}发布于 2013-03-12 23:15:30
fpath是一个野指针,即在调用strcpy之前没有为它分配任何存储空间。但是,由于您只需要一个const char *作为文件名,所以只需进行以下更改即可。
更改:
strcpy(fpath,argv[1]);至:
fpath = argv[1];发布于 2013-03-12 23:31:45
如果您想单独使用fpath,请更改您的定义:
char fpath[30];现在,您的strcpy将按预期工作(尽管您应该检查字符串的长度是否小于30)。但是,您可以直接将argv[1]传递给open,因为您不会对它做任何其他事情。
https://stackoverflow.com/questions/15364993
复制相似问题