简体   繁体   English

从未知大小的文件描述符中完全读取

[英]Reading fully from file descriptor of unknown size

I have used pipe and I have to read from this pipe. 我已经使用过管道,并且必须从该管道中阅读。 But problem is this: 但是问题是这样的:

ssize_t read(int fd, void *buf, size_t count)

I don't know how many characters is stored in the reading end of pipe, so I can't assign some number to count . 我不知道在管道的读取端中存储了多少个字符,因此我无法分配一些要计数的数字 I need this to store in the buffer. 我需要将此存储在缓冲区中。

How can I number of characters stored in this pipe? 如何在此管道中存储多少字符?

With regards 带着敬意

Just use a reasonably sized buffer, and read as much as you can. 只需使用大小适当的缓冲区,并尽可能多地读取。 Repeat that. 重复一遍。 The function returns the number of bytes read. 该函数返回读取的字节数。

I don't know how many characters is stored in the reading end of pipe 我不知道管道的读取端中存储了多少个字符

Don't worry about it. 不用担心 There are advantages (eg atomicity) to not trying to write/read more than PIPE_BUF bytes at shot. 有优点(例如原子性),即刻尝试不写/读超过PIPE_BUF个字节。 In reality you will probably get a bunch of short reads anyway. 实际上,无论如何,您可能都会得到一堆短篇小说。

#define READ_BUFFER_SIZE PIPE_BUF

unsigned char mybuffer[READ_BUFFER_SIZE];

ssize_t bytesread = 1;

while ((bytesread = read(pipefd, mybuffer, READ_BUFFER_SIZE)) > 0)
{
    concat to bigger buffer, realloc if necessary
}

You can simply request the number of characters up to the size of your buffer, and do so repeatedly in a loop, eg: 您可以简单地请求不超过缓冲区大小的字符数,然后在循环中重复执行此操作,例如:

char* buf = malloc(1024);
do {
   bytes_read = read(fd, buf, 1024);
   // store buf somewhere else so you can use it in the next iteration
} while (bytes_read > 0)
free(buf);

You need not know before hand how many bytes are there and pass that as as a value for count. 您无需事先知道有多少字节并将其作为计数值传递。 You can define buffer of maximum data size that you can expect and read from the fd until data is present. 您可以定义期望的最大数据大小的缓冲区,并从fd中读取数据,直到数据存在为止。

char buf[MAX_DATA_SIZE] = {0};

bytes_read = 0;
while(n > 0)
{
    n = read(fd,buf+bytes_read,MAX_DATA_SIZE)
    bytes_read = bytes_read + n;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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