繁体   English   中英

使用读写系统调用时是否需要使用while循环?

[英]Is it necessary to use a while loop when using the read and write system calls?

我正在练习读写系统调用,下面的代码在 while 循环和没有它们的情况下都可以正常工作。 你能告诉我这里的while循环有什么用吗,是否有必要在使用读写系统调用时添加它。 我是初学者。 谢谢。

#include <unistd.h>
#define BUF_SIZE 256
int main(int argc, char *argv[])
{
    char buf[BUF_SIZE];    
    ssize_t rlen;
    int i; 
    char from;
    char to;
    from = 'e';
    to = 'a';

    while (1) {
        rlen = read(0, buf, sizeof(buf));
        if (rlen == 0)
               return 0;

        for (i = 0; i < rlen; i++) {
               if (buf[i] == from)
                      buf[i] = to;
        }
    write(1, buf, rlen);
   }
return 0;
}


您通常需要在readwrite中使用while循环(或一般的某种循环),因为正如您应该从手册页( man 2 read )中知道的那样:

 RETURN VALUE On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of- file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. See also NOTES.

因此,如果您想读取超过 1 个字节,则需要在循环中执行此操作,因为read总是可以处理少于请求的数量。

同样, write也可以处理小于请求的大小(参见man 2 write ):

 RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). It is not an error if this number is smaller than the number of bytes requested; this may happen for example because the disk device was filled. See also NOTES. On error, -1 is returned, and errno is set appropriately.

这里唯一的区别是,当write返回0时,它不是错误或文件结束指示符,您应该重试写入。

您的代码几乎是正确的,因为它使用循环来继续读取,直到没有更多字节要读取(当read返回0时),但是有两个问题:

  1. 您应该在read后检查错误( rlen < 0 )。
  2. 当您使用write时,您还应该在那里添加一个循环,因为正如我刚才所说,即使write处理的字节数也可能少于请求的字节数。

您的代码的正确版本是:

#include <stdio.h>
#include <unistd.h>

#define BUF_SIZE 256

int main(int argc, char *argv[])
{
    char buf[BUF_SIZE];
    ssize_t rlen, wlen, written;
    char from, to;
    int i;

    from = 'e';
    to = 'a';

    while (1) {
        rlen = read(0, buf, sizeof(buf));

        if (rlen < 0) {
            perror("read failed");
            return 1;
        } else if (rlen == 0) {
            return 0;
        }

        for (i = 0; i < rlen; i++) {
            if (buf[i] == from)
                buf[i] = to;
        }

        for (written = 0; written < rlen; written += wlen) {
            wlen = write(1, buf + written, rlen - written);

            if (wlen < 0) {
                perror("write failed");
                return 1;
            }
        }
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM