Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <unistd.h>
- int max(int a, int b) {
- if (a < b) {
- return b;
- }
- return a;
- }
- int fill_buffer(int fd, char* buffer, int size) {
- int result = read(fd, buffer, size);
- int total_read = 0;
- if (result > 0) {
- total_read += result;
- while (total_read != size && result != 0) {
- result = read(fd, buffer + total_read, size - total_read);
- if (result < 0) {
- return result;
- }
- total_read += result;
- }
- return total_read;
- }
- return result;
- }
- struct FileContent read_file(int fd) {
- int SIZE = 4096;
- char buffer[SIZE];
- int result = fill_buffer(fd, buffer, SIZE);
- if (result == -1) {
- struct FileContent error;
- error.size = -1;
- error.data = NULL;
- return error;
- }
- struct FileContent content;
- content.size = 0;
- size_t capacity = result + 1;
- content.data = malloc(capacity * sizeof(*content.data));
- if (content.data == NULL) {
- content.size = -1;
- return content;
- }
- while (result > 0) {
- if (result + content.size > capacity) {
- int new_capacity = content.size + max(SIZE, capacity * 2);
- char* tmp = realloc(content.data, new_capacity);
- if (!tmp) {
- free(content.data);
- content.data = NULL;
- content.size = -1;
- return content;
- }
- content.data = tmp;
- capacity = new_capacity;
- }
- memcpy(content.data + content.size, buffer, result);
- content.size += result;
- result = fill_buffer(fd, buffer, SIZE);
- if (result == -1) {
- free(content.data);
- content.data = NULL;
- content.size = -1;
- return content;
- }
- }
- if (content.size >= capacity) {
- int new_capacity = content.size + 1;
- char* tmp = realloc(content.data, new_capacity);
- if (!tmp) {
- free(content.data);
- content.data = NULL;
- content.size = -1;
- return content;
- }
- content.data = tmp;
- capacity = new_capacity;
- }
- content.data[content.size] = '\0';
- return content;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement