c-在使用读写系统调用时,是否需要使用while循环



我正在练习读写系统调用,下面的代码可以很好地使用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;
}

您通常需要将while循环(或通常的某种循环(与readwrite一起使用,因为您应该从手册页面(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;
}

相关内容

最新更新