mirror of
https://gitlab.com/80486DX2-66/gists
synced 2024-11-10 06:42:02 +05:30
C: add pure_getline.*
This commit is contained in:
parent
3dfe8a8d14
commit
f5fd670db6
48
c-programming/pure_getline.c
Normal file
48
c-programming/pure_getline.c
Normal 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;
|
||||
}
|
18
c-programming/pure_getline.h
Normal file
18
c-programming/pure_getline.h
Normal 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 */
|
Loading…
Reference in New Issue
Block a user