繁体   English   中英

如何使用 read() 部分读取输入直到换行?

[英]How to partially read input until a new line using read()?

我正在尝试部分读取输入,直到输入新行“\n”。 但是如何使用 read() function 来做到这一点? 现在我已经进行了部分读取,直到终端界面退出并停止输入(在 linux 终端上按 ctrl+d),但不知道如何在输入新行时停止。 这是我的代码:

int fd = 0;
const size_t read_size = 100;
size_t size = read_size;
char *buff = malloc(size+1);
size_t offset = 0;
size_t res = 0;

while((res = read(fd, buff + offset, read_size)) > 0)
{
    offset += res;
    buff[offset] = '\0';
    if (offset + read_size > size)
    {
        size *= 2;
        buff = realloc(buff, size+1);
    }
}
return buff;

我正在尝试部分读取输入,直到输入新行“\n”。 但是如何使用 read() function 来做到这一点?

通过读取实现此目的的唯一方法是一次read一个字符。 读完'\n'字符后,停止。

如何检查正在阅读的内容?

while (read(fd, buf + offset, 1) == 1) {
  if (buf[offset] == '\n') break;
  offset += 1;
}

暂无
暂无

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

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