Created
August 26, 2017 17:37
-
-
Save akabab/089ebd6828efec3067cfab2a66dbe78a to your computer and use it in GitHub Desktop.
Read on a file descriptor (parameter nbytes)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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