You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
708 B
40 lines
708 B
10 years ago
|
#include "readline.h"
|
||
|
#include <stdlib.h>
|
||
|
#include <stdio.h>
|
||
|
|
||
|
char *read_line(FILE *file) {
|
||
9 years ago
|
int length = 0, size = 128;
|
||
10 years ago
|
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;
|
||
|
}
|
||
9 years ago
|
if (length == size) {
|
||
9 years ago
|
char *new_string = realloc(string, size *= 2);
|
||
|
if (!new_string) {
|
||
|
free(string);
|
||
10 years ago
|
return NULL;
|
||
|
}
|
||
9 years ago
|
string = new_string;
|
||
10 years ago
|
}
|
||
9 years ago
|
string[length++] = c;
|
||
10 years ago
|
}
|
||
9 years ago
|
if (length + 1 == size) {
|
||
9 years ago
|
char *new_string = realloc(string, length + 1);
|
||
|
if (!new_string) {
|
||
|
free(string);
|
||
10 years ago
|
return NULL;
|
||
|
}
|
||
9 years ago
|
string = new_string;
|
||
10 years ago
|
}
|
||
9 years ago
|
string[length] = '\0';
|
||
10 years ago
|
return string;
|
||
|
}
|