使用read(..)从stdin读取并找出缓冲区的大小 [英] Reading from stdin using read(..) and figuring out the size of the buffer

查看:290
本文介绍了使用read(..)从stdin读取并找出缓冲区的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以告诉我使用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读取并找出缓冲区的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆