简体   繁体   English

使用read(..)读取stdin并计算缓冲区的大小

[英]Reading from stdin using read(..) and figuring out the size of the buffer

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: 我想知道是否有人可以告诉我,当使用read(...)从stdin read(...)输入时是否有动态分配缓冲区的方法例如:

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 ? 如何确保从stdin (此处为0)读取的字节数与buffer的相同?

You can't. 你不能。 You do a read into a fixed-size buffer, eg: 您可以read固定大小的缓冲区,例如:

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). 然后弄清楚是否还有更多数据可用(通常通过检查num_read是否等于BUF_SIZE ,但在某些情况下,您可能需要解释数据本身)。 If there is, then you do another read. 如果有,那么你再做一次阅读。 And so on. 等等。

It's up to you to deal with concatenating all the read data. 由您来处理连接所有读取数据。

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. 但是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM