gpt4 book ai didi

c - 读(): Invalid arguments

转载 作者:太空宇宙 更新时间:2023-11-04 05:54:42 24 4
gpt4 key购买 nike

我正在尝试在功能良好的 open() 返回的文件描述符上使用 read() 读取二进制文件,但它无法返回 22errno

代码如下:

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

最佳答案

我认为这可能与您的 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可能有帮助的简短教程

关于c - 读(): Invalid arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30390440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com