nurgasemetey
nurgasemetey

Reputation: 770

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

Upvotes: 2

Views: 4082

Answers (4)

Duck
Duck

Reputation: 27552

I don't know how many characters is stored in the reading end of pipe

Don't worry about it. There are advantages (e.g. atomicity) to not trying to write/read more than PIPE_BUF bytes at shot. 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
}

Upvotes: 2

bcr
bcr

Reputation: 1328

You can simply request the number of characters up to the size of your buffer, and do so repeatedly in a loop, e.g:

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);

Upvotes: 1

Prabhu
Prabhu

Reputation: 3541

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.

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;
}

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45674

Just use a reasonably sized buffer, and read as much as you can. Repeat that. The function returns the number of bytes read.

Upvotes: 2

Related Questions