我正在尝试开发一个概念验证程序,它可以打开一个文件、读取一些数据并关闭它,所有这些都不需要使用 fopen/getc/fclose 函数。相反,我正在使用低级别的打开/读取/关闭等价物但没有运气:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
int main ( int argc, char **argv ) {
int fp;
ssize_t num_bytes;
if ( fp = open ( "test.txt", O_RDONLY ) < 0 ) {
perror("Error opening file");
return 1;
}
char header[2];
while ( num_bytes = read ( fp, &header, 2 ) > 0 )
printf("read %i bytes\n", num_bytes);
printf("done reading\n");
close ( fp );
return 0;
}
如果不存在文件,正确打开会打印一条错误消息。另一方面,如果该文件存在,则程序会无缘无故地停在 read() 函数处。有什么帮助吗?
最佳答案
由于 operator precedence,这是不正确的:
if ( fp = open ( "test.txt", O_RDONLY ) < 0 )
作为=
优先级低于 <
.这意味着 fp
将被分配 0
或 1
, 取决于 open ( "test.txt", O_RDONLY ) < 0
的结果.
- 当文件不存在时条件为
-1 < 0
, 结果是1
和fp
已分配1
和if
进入分支。 - 当文件确实存在时,条件是
N < 0
(其中N
将大于两个由于stdin
、stdout
和stderr
占用文件描述符0
、1
和2
)和fp
已分配0
和if
分支没有进入。然后程序继续到read()
。行但fp
的值为0
,即stdin
所以它在等待从stdin
中读取内容时停止.
更改为:
if ( (fp = open ( "test.txt", O_RDONLY )) < 0 )
同样的问题:
while ( num_bytes = read ( fp, &header, 2 ) > 0 )
关于c - 我无法使打开/读取/关闭低级功能在 Ubuntu 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15975594/