【问题标题】:i can't make open/read/close low level functions to work in Ubuntu我无法使打开/读取/关闭低级功能在 Ubuntu 中工作
【发布时间】:2013-04-12 15:43:28
【问题描述】:

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

【问题讨论】:

    标签: c linux posix


    【解决方案1】:

    由于operator precedence,这是不正确的:

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

    因为= 的优先级低于&lt;。这意味着fp 将被分配01,这取决于open ( "test.txt", O_RDONLY ) &lt; 0 的结果。

    • 当文件不存在时,条件为-1 &lt; 0,其结果为1fp赋值1,进入if分支。
    • 当文件确实存在时,条件为N &lt; 0(其中N 将大于两个由于stdinstdoutstderr 占用文件描述符012 ) 并且fp 被分配0 并且if 分支没有进入。然后程序继续执行read() 行,但fp 的值为0,即stdin,因此它在等待从stdin 读取内容时停止。

    改为:

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

    同样的问题:

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

    【讨论】:

    • 显然我应该更仔细地检查 gcc 通过 -Wall 开关报告的内容
    【解决方案2】:

    改变这个:

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

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

    【讨论】:

      【解决方案3】:

      '' 优先于 '='

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

      修改如下代码,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-06
        • 2012-12-29
        • 1970-01-01
        • 2013-12-25
        • 1970-01-01
        • 1970-01-01
        • 2016-06-08
        • 1970-01-01
        相关资源
        最近更新 更多