问题描述
我想知道是否有人可以告诉我使用read(...)
从stdin读取输入时是否有一种动态分配缓冲区的方法例如:
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 ?);
如何确保从stdin
读取的字节数(此处为0)与buffer
中的字节数相同?
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
?
推荐答案
您不能.您将read
放入固定大小的缓冲区中,例如:
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);
,然后找出是否还有其他可用数据(通常通过检查num_read
是否等于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.
这篇关于使用read(..)从stdin读取并找出缓冲区的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!