//open file
if((fd = open("test.txt", O_RDWR | O_APPEND)) == -1)
printf("open failed\n");
//set offset
if(lseek(fd, -8, SEEK_CUR) == -1)
printf("cannot seek\n");
then it print “cannot seek”,this is why?
after strerrno(errno),it shows “Invalid argument”
Now I find the problem,the SEEK_CUR is at the start position.
But Why? I use append mode.
It works for me when I ensure that the current position when seeking is at least 8, so that
doesn’t try to set the position before the start of the file.
If
lseekwould set the file position to a negative offset, it setserrnotoEINVAL, which is reported as anInvalid argument, just as you observed.Note that
opensets the current file position to the beginning of the file (at least my glibc’sopendoes), so you’d need tolseek(fd,-8,SEEK_END)if you want to set the position eight bytes from the end. But of course that would still fail if the file is smaller than eight bytes.