0

我正在尝试开发一个概念验证程序,它可以打开文件、读取一些数据并关闭它,所有这些都不使用 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() 函数处停止,没有明显的原因。对此有什么帮助吗?

4

3 回答 3

6

由于运算符优先级,这是不正确的:

if ( fp = open ( "test.txt", O_RDONLY ) < 0 )

as=的优先级低于<. 这意味着fp将根据 的结果分配0或。1open ( "test.txt", O_RDONLY ) < 0

  • 当文件不存在时,条件是-1 < 0,结果是1fp被赋值1if进入分支。
  • 当文件确实存在时,条件是N < 0(where Nwill be greater than two due stdinstdout并且stderr占用文件描述符01and 2)并且fp被赋值0并且if不进入分支。然后程序继续执行该read()行,但fp值为0stdin因此它在等待从 读取内容时停止stdin

改成:

if ( (fp = open ( "test.txt", O_RDONLY )) < 0 )

这里同样的问题:

while ( num_bytes = read ( fp, &header, 2 ) > 0 )
于 2013-04-12T15:44:53.930 回答
1

改变这个:

while ( num_bytes = read ( fp, &header, 2 ) > 0 )

while ( (num_bytes = read ( fp, &header, 2 )) > 0 )
于 2013-04-12T15:45:58.107 回答
0

'<' 或 >' 优先于 '='

所以比较结果是''0'或'1'将被分配给fp。

修改如下代码,

if ( (fp = open ( "test.txt", O_RDONLY )) < 0 )

于 2013-04-12T16:29:12.627 回答