问题描述
我写了这个小code,以确定读的行为。
I wrote this small code to ascertain read behavior.
#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的语句
But if I change lseek statement to
ret = lseek(fd,5,SEEK_SET);
read返回0
read returns 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
为什么读这样的表现?
Why does read behave like this?
推荐答案
请注意,通过 lseek的
返回的值是一个 off_t
,而不是为size_t
。所不同的是off_t签署。当你把一个符号值,使之无符号,它看起来像一个大的正数。
Note that the value returned by lseek
is a off_t
, not a size_t
. The difference is that off_t is signed. When you take a signed value and make it unsigned, it appears like a large positive number.
我预计LONG_MAX其实不是 4294967295
,但无论是 2147483647
(2 ^ 31-1 ),或者一个更大的数。因此 4294967295
来自-1 [它是2 ^ 32-1,这确实是在32位的运算一样-1]。
I would expect that "LONG_MAX" is not actually 4294967295
, but either 2147483647
(2^31-1) or a much larger number. So the 4294967295
comes from a -1 [it is 2^32-1, which is indeed the same as -1 in 32-bit math].
在换句话说,你都可以从 lseek的
错误。
In other words, you are getting an error from lseek
.
这篇关于UNIX阅读行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!