我编写了这个小代码来确定读取行为。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>
int main ()
{
ssize_t ret;
int fd;
char str[30] = {0};
off_t lret
fd = open("./sample", O_RDWR);
printf("File descriptor = %d\n",fd);
lret = lseek(fd,LONG_MAX,SEEK_SET);
printf("%ld\n",lseek(fd, 0, SEEK_CUR));
ret = read(fd, str, 20);
if (ret == -1) {
perror("read error");
}
else {
printf("%ld\n",ret);
printf("%s\n",str);
}
ret = write(fd, "bye", 3);
if (ret == -1) {
perror("write error");
}
else
printf("%ld\n",ret);
printf("%ld\n",lseek(fd, 0, SEEK_CUR));
close (fd);
return 0;
}
这是输出:
$ cat sample
HELLO$ ./a.out
File descriptor = 3
4294967295
read error: Invalid argument
write error: Invalid argument
4294967295
$ ll sample
-rw-r--r--. 1 bruce stud 5 Jan 14 17:25 sample
但是如果我将 lseek 语句更改为
ret = lseek(fd,5,SEEK_SET);
读取返回 0
$ ./a.out
File descriptor = 3
5
0
3
8
$ cat sample
HELLObye$ ll sample
-rw-r--r--. 1 bruce stud 8 Jan 14 17:26 sample
为什么 read 会有这样的行为?