开发者

Read from stdin

It seems as if read(0, buffer, 255) always returns 1 when reading. In my program I direct input through the pipe into this program, but I noticed that it always returned a 1. Why is this? Is there a better way of doing this? At the same time, it开发者_运维问答 seems to fill up the buffer properly, past the 1 char.

Thank you in advance!


read is allowed to return less characters than you asked for, so you should code for that eventuality rather than trying to find a way to avoid it.

For example, if there's only 22 bytes left in the file (or the pipe), it will give you those bytes.

From the Linux man page (since read is a POSIX thing rather than a C++ thing):

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.

If the rest of your buffer seems to be populated correctly, I can assure you that it's entirely by accident and you shouldn't rely on that. If read returns 1, then only use that one character. If you follow the rules and characters seem to disappear, then you can come back and complain about a buggy read implementation (I shouldn't need to point out that this is incredibly unlikely).

Try the following program:

#include <stdio.h>
#include <stdlib.h>

int main (void) {
    char buff[255];
    int i;

    while ((i = read (0, buff, 255)) > 0) {
        printf ("%3d: [%*.*s]\n", i, i, i, buff);
    }

    return 0;
}

with:

echo hello there | ./tstprg ; (echo hello ; sleep 1 ; echo there) | ./tstprg

and see what you get. My output is:

 12: [hello there
]
  6: [hello
]
  6: [there
]

as I expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜