【问题标题】:Assigning value inside while condition在while条件内赋值
【发布时间】:2021-05-04 13:05:16
【问题描述】:

我正在尝试将 read 的返回值分配给一个变量,同时在 while 条件内检查该值的条件。

while(reader=(read(fd, temp, BUFFER_SIZE)) >= BUFFER_SIZE)

但不是分配正确的值,而是分配条件的值(0或1)。 我该如何解决这个问题?我需要将它分配给一个变量,因为我会在之后使用它,并且我不能在循环中声明它。

【问题讨论】:

    标签: c loops conditional-statements variable-assignment


    【解决方案1】:

    赋值必须用括号括起来,而不仅仅是函数调用:

    while ((reader = read(fd, temp, BUFFER_SIZE)) >= BUFFER_SIZE) ...
    

    但是请注意,读取的字节数不能大于请求的字节数,并且取决于reader 的类型和符号,比较将使用有符号或无符号算术,使-1 的返回值大于@ 987654324@。为避免这种情况,reader 必须定义为 ssize_t 或其他一些有符号类型。

    更复杂的是,BUFFER_SIZE 可以定义为无符号数量,例如 #define BUFFER_SIZE 4096U#define BUFFER_SIZE sizeof(temp),即使 reader 具有有符号类型,这也会强制执行无符号算术...

    这是一种更安全的方法:

        unsigned char temp[BUFFER_SIZE];
        ssize_t nread;
    
        while ((nread = read(fd, temp, sizeof temp)) > 0) {
            // handle nread bytes...
        }
        if (nread < 0) {
            // handle read error
        } else {
            // reached end of file successfully
        }
    

    上述循环不会处理可能导致read 返回-1 的信号。 你可以为此添加一个特殊的测试:

        unsigned char temp[BUFFER_SIZE];
        ssize_t nread;
    
        for (;;) {
            nread = read(fd, temp, sizeof temp);
            if (nread < 0) {
                if (errno == EINTR) {
                    // read attempt was interrupted by signal, restart
                    continue;
                }
                fprintf(stderr, "read error: %s\n", strerror(errno));
                break;
            }
            if (nread == 0) {
                // normal end of file
                break;
            }
            // handle nread bytes...
        }
    

    【讨论】:

      【解决方案2】:

      &gt;= 的优先级高于=。您编写代码的方式相当于执行以下操作:

      1. TEMP = read(fd, temp, BUFFER_SIZE);
      2. reader = (TEMP) &gt;= BUFFER_SIZE;

      由于优先规则,在 reader 中存储一个布尔值。

      您想要的是将TEMP 存储到reader 中并将readerBUFFER_SIZE 进行比较,然后您需要放置一些括号,以便在比较之前完成分配,这会将2. 更改为: (reader = TEMP) &gt;= BUFFER_SIZE;

      所以你的代码应该是:

      while((reader= read(fd, temp, BUFFER_SIZE)) >= BUFFER_SIZE)
      

      【讨论】:

        猜你喜欢
        • 2020-10-27
        • 2010-11-11
        • 1970-01-01
        • 2011-12-08
        • 2019-05-29
        • 2015-08-29
        • 1970-01-01
        • 2016-01-13
        相关资源
        最近更新 更多