c - 我无法使打开/读取/关闭低级功能在 Ubuntu 中工作

标签 c linux posix

我正在尝试开发一个概念验证程序,它可以打开一个文件、读取一些数据并关闭它,所有这些都不需要使用 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将被分配 01 , 取决于 open ( "test.txt", O_RDONLY ) < 0 的结果.

  • 当文件不存在时条件为-1 < 0 , 结果是 1fp已分配 1if进入分支。
  • 当文件确实存在时,条件是N < 0 (其中 N 将大于两个由于 stdinstdoutstderr 占用文件描述符 012 )和 fp已分配 0if分支没有进入。然后程序继续到 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/

相关文章:

linux - VMWare Server Under Linux Secondary NIC 连接

windows - 如何在不关闭 session 的情况下从Linux远程控制Windows

c - 对象WMA(虚拟内存区域:) and PTE (Page Table Entry)?)之间有什么区别

c - 在现代 POSIX 环境中除了 usleep 还能用什么?

c - 如何不使用 waitpid 阻止父级

c - 如何将 void* 转换为 int[][3]

c - C中如何将相对路径转换为绝对路径?

c++ - 从 C/C++ 中的周数计算公历日期

C 使用 Strtol 将字符串解析为两个整数

linux - Swift - 读取管道输入