1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-12-27 05:40:17 +05:30

C: add pure_getline.*

This commit is contained in:
Intel A80486DX2-66 2024-01-28 22:47:01 +03:00
parent 3dfe8a8d14
commit f5fd670db6
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B
2 changed files with 66 additions and 0 deletions

View File

@ -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;
}

View File

@ -0,0 +1,18 @@
/*
* pure_getline.h
*
* Author: Intel A80486DX2-66
* License: Creative Commons Zero 1.0 Universal
*/
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef _PURE_GETLINE_H
#define _PURE_GETLINE_H
bool pure_getline(char** output);
#endif /* _PURE_GETLINE_H */