Last active
October 31, 2021 11:26
-
-
Save iharkatkavets/9b8cf0bdafe3026d5bf00c2edbbcfb7e to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <stdbool.h> | |
#include <strings.h> | |
char* readline() { | |
size_t alloc_length = 1024; | |
size_t data_length = 0; | |
char *data = (char *)malloc(alloc_length); | |
while (true) { | |
char *cursor = data + data_length; | |
char *line = fgets(cursor, alloc_length-data_length, stdin); | |
if (line == NULL && !data_length) { | |
free(data); | |
data = NULL; | |
break; | |
} | |
data_length += strlen(line); | |
if (data_length < alloc_length) { break; } | |
alloc_length <<= 1; | |
data = (char *)realloc(data, alloc_length); | |
if (!data) { break; } | |
} | |
if (data == NULL) { | |
return data; | |
} | |
if (data[data_length] != '\0') { | |
data[++data_length] = '\0'; | |
} | |
if (data_length < alloc_length) { | |
data = (char *)realloc(data, data_length); | |
} | |
return data; | |
} | |
char* read_stdin() { | |
size_t alloc_length = 1024; | |
size_t data_length = 0; | |
char *data = (char *)malloc(alloc_length); | |
while (true) { | |
char *cursor = data + data_length; | |
ssize_t read_length = read(STDIN_FILENO, cursor, alloc_length-data_length); | |
if (!read_length && !data_length) { | |
free(data); | |
data = NULL; | |
break; | |
} | |
data_length += read_length; | |
if (data_length < alloc_length) { break; } | |
alloc_length <<= 1; | |
data = (char *)realloc(data, alloc_length); | |
if (!data) { break; } | |
} | |
if (data == NULL) { | |
return data; | |
} | |
if (data[data_length] != '\0') { | |
data[++data_length] = '\0'; | |
} | |
if (data_length < alloc_length) { | |
data = (char *)realloc(data, data_length); | |
} | |
return data; | |
} | |
int main(int argc, char **argv) { | |
char* (*fun_ptr)() = &read_stdin;// &readline; | |
char *buffer = fun_ptr(); | |
int i=0; | |
while(buffer != NULL) { | |
printf("\n%d %s", i, buffer); | |
free(buffer); | |
i++; | |
buffer = fun_ptr(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment