diff --git a/c-programming/pure_getline.c b/c-programming/pure_getline.c new file mode 100644 index 0000000..1411e59 --- /dev/null +++ b/c-programming/pure_getline.c @@ -0,0 +1,48 @@ +/* + * pure_getline.c + * + * Author: Intel A80486DX2-66 + * License: Creative Commons Zero 1.0 Universal +*/ + +#include "pure_getline.h" + +bool pure_getline(char** output) { + /* + * return value: + * true: no errors + * false: an error occurred, see errno + */ + + char* line = NULL; + size_t len = 0; + int character; + bool past_first_time = false; + + while ((character = fgetc(stdin)) != EOF) { + if (past_first_time && len == 0) { // check for integer overflow + errno = ERANGE; + *output = NULL; + return false; + } + + char* new_line = realloc(line, (len + 1) * sizeof(char)); + + if (new_line == NULL) { + *output = line; + return false; + } + + line = new_line; + + if (character == '\n') { + line[len] = '\0'; + break; + } + line[len++] = character; + past_first_time = true; + } + + *output = line; + return true; +} diff --git a/c-programming/pure_getline.h b/c-programming/pure_getline.h new file mode 100644 index 0000000..6fcf5c7 --- /dev/null +++ b/c-programming/pure_getline.h @@ -0,0 +1,18 @@ +/* + * pure_getline.h + * + * Author: Intel A80486DX2-66 + * License: Creative Commons Zero 1.0 Universal + */ + +#include +#include +#include +#include + +#ifndef _PURE_GETLINE_H +#define _PURE_GETLINE_H + +bool pure_getline(char** output); + +#endif /* _PURE_GETLINE_H */