Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- enum { MAXIMUM_SIZE = 4096 };
- struct FileContent {
- ssize_t size;
- char *data;
- };
- ssize_t inputAmount(int fd, char *buf) {
- ssize_t symbols = 0;
- while (symbols < MAXIMUM_SIZE) {
- ssize_t readPart = read(fd, buf + symbols, MAXIMUM_SIZE - symbols);
- if (readPart == -1) {
- return -1;
- } else if (readPart == 0){
- return symbols;
- }
- symbols += readPart;
- }
- return symbols;
- }
- struct FileContent read_file(int fd) {
- ssize_t symbols = 0, readedSymbols = 0, memSize = 1;
- struct FileContent badExit = { -1, NULL };
- char *data = malloc(sizeof(*data));
- char buf[MAXIMUM_SIZE];
- if (!data) {
- return badExit;
- }
- int reading = 1;
- while (reading) {
- ssize_t reading = inputAmount(fd, buf);
- if (reading == -1) {
- free(data);
- return badExit;
- }
- if (!reading) {
- break;
- }
- while (readedSymbols + symbols >= memSize) {
- memSize *= 2;
- }
- char * copydata = realloc(data, memSize * sizeof(*copydata));
- if (!copydata) {
- free(data);
- return badExit;
- }
- data = copydata;
- memcpy(data + readedSymbols, buf, symbols);
- readedSymbols += symbols;
- }
- data[readedSymbols] = 0;
- badExit.size = readedSymbols;
- badExit.data = data;
- return badExit;
- };
- int main(int argc, char **argv) {
- int fd = open("in.txt", O_RDONLY);
- printf("%d\n", fd);
- struct FileContent kek = read_file(fd);
- printf("%d\n", kek.size);
- for (int i = 0; i < kek.size; ++i) {
- printf("%c", kek.data[i]);
- }
- printf("\n");
- free(kek.data);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement