Read from pipe line by line in C

社会主义新天地 提交于 2019-12-03 06:53:13

This is usually just called reading from stdin. The program shouldn't care whether the input is a pipe, a redirected file, or a keyboard.

fread will just read until the buffer is full. Use fgets to read a line.

Also the buffer size should be big enough to hold the line. For little one-off programs, you can just pick a number. Or there's a standard name BUFSIZ which gives you a pretty-big buffer. How big? Big enough. Really? Probably.

fgets will copy the newline character in the string unless the string fills up first. So you can test the last character to tell if the line was truncated or not. With reasonable inputs, that's not going to happen. But a more robust approach would allocate a larger buffer, copy the partial line, and call fgets again tp keep trying to get a complete line.

#include <stdio.h>

int main() {
    char buf[BUFSIZ];
    fgets(buf, sizeof buf, stdin);
    if (buf[strlen(buf)-1] == '\n') {
        // read full line
    } else {
        // line was truncated
    }
    return 0;
}

This gets you halfway to being protected from the dreaded buffer overflow problem. fgets will not write more than the size passed to it. The other half, as mentioned above, is doing something sensible with the possible partial lines that may result from unexpectedly long input lines.

Here's another option (I am not totally sure it is a 'proper' way)- use the number of bytes read by the read function. In this example I was reading from stdin although a redirection was made so the fd in 0 is a file/pipe/whatever you need it to be.

  while ((nbytes=read(STDIN_FILENO, buffer, MAX_PIPE_SIZE)) > 0) {
    write(STDOUT_FILENO, buffer, nbytes);
  }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!