2015-08-05 11:30:40 +10:00
|
|
|
#include "readline.h"
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
char *read_line(FILE *file) {
|
2015-08-18 18:32:54 +10:00
|
|
|
int length = 0, size = 128;
|
2015-08-05 11:30:40 +10:00
|
|
|
char *string = malloc(size);
|
|
|
|
if (!string) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
while (1) {
|
|
|
|
int c = getc(file);
|
|
|
|
if (c == EOF || c == '\n' || c == '\0') {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (c == '\r') {
|
|
|
|
continue;
|
|
|
|
}
|
2015-08-18 18:32:54 +10:00
|
|
|
if (length == size) {
|
|
|
|
string = realloc(string, size *= 2);
|
2015-08-05 11:30:40 +10:00
|
|
|
if (!string) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
}
|
2015-08-18 18:32:54 +10:00
|
|
|
string[length++] = c;
|
2015-08-05 11:30:40 +10:00
|
|
|
}
|
2015-08-18 18:32:54 +10:00
|
|
|
if (length + 1 == size) {
|
2015-08-05 11:30:40 +10:00
|
|
|
string = realloc(string, length + 1);
|
|
|
|
if (!string) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
}
|
2015-08-18 18:32:54 +10:00
|
|
|
string[length] = '\0';
|
2015-08-05 11:30:40 +10:00
|
|
|
return string;
|
|
|
|
}
|