[英]Reading from stdin using read(..) and figuring out the size of the buffer
我想知道是否有人可以告诉我,当使用read(...)
从stdin read(...)
输入时是否有动态分配缓冲区的方法例如:
n = read(0, buffer, sizeof ?);
如何确保从stdin
(此处为0)读取的字节数与buffer
的相同?
你不能。 您可以read
固定大小的缓冲区,例如:
char buf[BUF_SIZE];
int num_read = read(0, buf, BUF_SIZE);
然后弄清楚是否还有更多数据可用(通常通过检查num_read
是否等于BUF_SIZE
,但在某些情况下,您可能需要解释数据本身)。 如果有,那么你再做一次阅读。 等等。
由您来处理连接所有读取数据。
你不能(除非你有预知技能)弄清楚你会得到什么的大小。
但是read方法允许你逐个读取stdin的内容,如果你将read()调用放入( while your_stop_condition
)循环中,你将能够通过数据包读取stdin所需的所有东西。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.