Skip to content

Instantly share code, notes, and snippets.

@akabab
Created August 26, 2017 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akabab/089ebd6828efec3067cfab2a66dbe78a to your computer and use it in GitHub Desktop.
Save akabab/089ebd6828efec3067cfab2a66dbe78a to your computer and use it in GitHub Desktop.
Read on a file descriptor (parameter nbytes)
/*
idea was to resolve unexpected short-reads (when reading on stdin or pipe), read was returning less bytes than asked
cf. https://stackoverflow.com/a/8975581/5183171
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *read_fd(int fd, int nbyte)
{
char *input;
char buffer[nbyte + 1];
int bytes_read;
int n;
char *tmp;
n = 1;
input = NULL;
while ((bytes_read = read(fd, buffer, nbyte)) > 0)
{
buffer[bytes_read] = '\0';
tmp = malloc((n * nbyte + 1) * sizeof(char));
tmp[0] = '\0';
if (input)
{
strcpy(tmp, input);
free(input);
}
input = strcat(tmp, buffer);
n++;
}
if (bytes_read == -1)
return (NULL);
return (input);
}
#define NBYTE 100
int main(void)
{
printf("%s", read_fd(0, NBYTE));
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment