问题
I was wondering if anyone could tell me if there is a way to dynamically allocate a buffer when reading an input from stdin using read(...)
For example:
n = read(0, buffer, sizeof ?);
How do I ensure that the number of bytes read from stdin
(here 0) is the same as in buffer
?
回答1:
You can't. You do a read
into a fixed-size buffer, e.g.:
char buf[BUF_SIZE];
int num_read = read(0, buf, BUF_SIZE);
and then figure out if there's any more data available (usually by checking whether num_read
is equal to BUF_SIZE
, but in some cases, maybe you need to interpret the data itself). If there is, then you do another read. And so on.
It's up to you to deal with concatenating all the read data.
回答2:
You can't (unless you've got precognitive skills) figure out the size of what you will get.
But the read method allow you to read part by part the content of stdin, if you put your read() call into a (while your_stop_condition
) loop, you will be able to read all the stuff you need from stdin, by packets.
char buffer_to_read[SIZE];
int bytes=0;
while your_stop_condition
{
bytes = read(0, buffer_to_read, SIZE);
// do what you want with your data read
// if bytes < SIZE, you read an EOF
}
来源:https://stackoverflow.com/questions/7503399/reading-from-stdin-using-read-and-figuring-out-the-size-of-the-buffer