read() :无效参数
read() : Invalid arguments
我正在尝试使用 read()
在功能良好的 open()
返回的文件描述符上读取二进制文件,但它无法返回 22
和 errno
.
这是代码:
int input = open(argv[1], O_RDONLY|O_DIRECT);
char buffer_header[4];
if(read(input,buffer_header,4) > 0)
image_width = bytesToInt(buffer_header);
printf("%d\n",errno);
发生的情况是 read()
上的条件不匹配。难道我做错了什么?返回的文件描述符是 3
.
如果 read
returns -1
您应该只检查 errno
以表明它有错误。
int n;
if ((n = read(input, buffer_header, 4)) > 0) {
image_width = bytesToInt(buffer_header);
} else if (n == -1) {
perror("read");
} else {
printf("EOF\n");
}
我认为这可能与您的 if 语句 > 0 有关。
read
手册页的内容如下(在终端中输入 man 2 read):
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if
this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because
we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is
returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.
所以你的代码应该是这样的
if(-1 == read(input,buffer_header,4)) {
perror("error with read");
} else {
do something;
}
编辑:抱歉,刚刚看到评论感谢 Barmar!!
Edit2:您还应该类似地错误检查 open
系统调用。
int input = open(argv[1], O_RDONLY|O_DIRECT);
if(-1 == input) {
perror("error with open");
} else {
do stuff;
}
Here's 可能有用的简短教程
我正在尝试使用 read()
在功能良好的 open()
返回的文件描述符上读取二进制文件,但它无法返回 22
和 errno
.
这是代码:
int input = open(argv[1], O_RDONLY|O_DIRECT);
char buffer_header[4];
if(read(input,buffer_header,4) > 0)
image_width = bytesToInt(buffer_header);
printf("%d\n",errno);
发生的情况是 read()
上的条件不匹配。难道我做错了什么?返回的文件描述符是 3
.
如果 read
returns -1
您应该只检查 errno
以表明它有错误。
int n;
if ((n = read(input, buffer_header, 4)) > 0) {
image_width = bytesToInt(buffer_header);
} else if (n == -1) {
perror("read");
} else {
printf("EOF\n");
}
我认为这可能与您的 if 语句 > 0 有关。
read
手册页的内容如下(在终端中输入 man 2 read):
RETURN VALUE On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.
所以你的代码应该是这样的
if(-1 == read(input,buffer_header,4)) {
perror("error with read");
} else {
do something;
}
编辑:抱歉,刚刚看到评论感谢 Barmar!!
Edit2:您还应该类似地错误检查 open
系统调用。
int input = open(argv[1], O_RDONLY|O_DIRECT);
if(-1 == input) {
perror("error with open");
} else {
do stuff;
}
Here's 可能有用的简短教程