Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <unistd.h>
- enum { BUFFER_SIZE = 4096 };
- ssize_t read_BUFF(int in_fd, char *buffer) {
- ssize_t count_read = 0;
- while (count_read != BUFFER_SIZE) {
- ssize_t read_bytes = read(in_fd, buffer + count_read,
- BUFFER_SIZE - count_read);
- if (read_bytes == -1) {
- return -1;
- }
- if (read_bytes == 0) {
- return count_read;
- }
- count_read += read_bytes;
- }
- return BUFFER_SIZE;
- }
- struct FileContent read_file(int fd) {
- errno = !ENOMEM;
- struct FileContent returned;
- char buffer[BUFFER_SIZE];
- char *data = malloc(sizeof(*data));
- if (errno == ENOMEM) {
- free(data);
- returned.size = -1;
- returned.data = NULL;
- return returned;
- }
- size_t cur_mal = 1;
- if (data == NULL) {
- free(data);
- returned.size = -1;
- returned.data = NULL;
- return returned;
- }
- ssize_t read = 1;
- ssize_t current_read = 0;
- while (read > 0) {
- read = read_BUFF(fd, buffer);
- if (read == -1) {
- free(data);
- returned.size = -1;
- returned.data = NULL;
- return returned;
- }
- while (current_read + read >= cur_mal) {
- char *data1;
- data1 = realloc(data, (cur_mal *= 2) * sizeof(*data));
- if (data1 == NULL) {
- free(data);
- returned.size = -1;
- returned.data = NULL;
- return returned;
- } else {
- data = data1;
- }
- if (errno == ENOMEM) {
- free(data);
- returned.size = -1;
- returned.data = NULL;
- return returned;
- }
- }
- memcpy(data + current_read, buffer, read);
- current_read += read;
- }
- returned.size = current_read;
- data[current_read] = 0;
- returned.data = data;
- return returned;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement