Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "attachments/read_file.h"
- #include <stdlib.h>
- #include <unistd.h>
- struct FileContent read_file(int fd) {
- struct FileContent result;
- char *buf = calloc(4096, 1);
- if (buf == NULL) {
- result.size = -1;
- result.data = NULL;
- return result;
- }
- char *cur_buf = buf;
- size_t file_size = 0;
- size_t file_capacity = 4096;
- ssize_t read_res = read(fd, cur_buf, file_capacity);
- while (read_res > 0) {
- file_size += read_res;
- cur_buf += read_res;
- if (file_size == file_capacity) {
- file_capacity <<= 1;
- char *new_buf = realloc(buf, file_capacity);
- if (new_buf == NULL) {
- free(buf);
- result.size = -1;
- result.data = NULL;
- return result;
- }
- buf = new_buf;
- cur_buf = buf + file_size;
- }
- read_res = read(fd, cur_buf, file_capacity - file_size);
- }
- if (read_res == 0) {
- *cur_buf = 0;
- result.size = file_size;
- result.data = buf;
- return result;
- } else {
- result.size = -1;
- result.data = NULL;
- return result;
- }
- }
- #include <fcntl.h>
- #include <stdio.h>
- int main(int argc, char *argv[]) {
- struct FileContent file_content = read_file(open(argv[1], O_RDONLY));
- printf("%zu\n%s", file_content.size, file_content.data);
- free(file_content.data);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement