2015-08-05 01:30:40 +00:00
|
|
|
#include "readline.h"
|
2016-12-15 22:08:56 +00:00
|
|
|
#include "log.h"
|
2015-08-05 01:30:40 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
char *read_line(FILE *file) {
|
2016-01-28 12:56:46 +00:00
|
|
|
size_t length = 0, size = 128;
|
2015-08-05 01:30:40 +00:00
|
|
|
char *string = malloc(size);
|
2016-06-05 22:17:27 +00:00
|
|
|
char lastChar = '\0';
|
2015-08-05 01:30:40 +00:00
|
|
|
if (!string) {
|
2018-01-05 21:32:51 +00:00
|
|
|
wlr_log(L_ERROR, "Unable to allocate memory for read_line");
|
2015-08-05 01:30:40 +00:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
while (1) {
|
|
|
|
int c = getc(file);
|
2016-06-05 22:17:27 +00:00
|
|
|
if (c == '\n' && lastChar == '\\'){
|
|
|
|
--length; // Ignore last character.
|
|
|
|
lastChar = '\0';
|
|
|
|
continue;
|
|
|
|
}
|
2015-08-05 01:30:40 +00:00
|
|
|
if (c == EOF || c == '\n' || c == '\0') {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (c == '\r') {
|
|
|
|
continue;
|
|
|
|
}
|
2016-06-05 22:17:27 +00:00
|
|
|
lastChar = c;
|
2015-08-18 08:32:54 +00:00
|
|
|
if (length == size) {
|
2015-08-20 00:24:47 +00:00
|
|
|
char *new_string = realloc(string, size *= 2);
|
|
|
|
if (!new_string) {
|
|
|
|
free(string);
|
2018-01-05 21:32:51 +00:00
|
|
|
wlr_log(L_ERROR, "Unable to allocate memory for read_line");
|
2015-08-05 01:30:40 +00:00
|
|
|
return NULL;
|
|
|
|
}
|
2015-08-20 00:24:47 +00:00
|
|
|
string = new_string;
|
2015-08-05 01:30:40 +00:00
|
|
|
}
|
2015-08-18 08:32:54 +00:00
|
|
|
string[length++] = c;
|
2015-08-05 01:30:40 +00:00
|
|
|
}
|
2015-08-18 08:32:54 +00:00
|
|
|
if (length + 1 == size) {
|
2015-08-20 00:24:47 +00:00
|
|
|
char *new_string = realloc(string, length + 1);
|
|
|
|
if (!new_string) {
|
|
|
|
free(string);
|
2015-08-05 01:30:40 +00:00
|
|
|
return NULL;
|
|
|
|
}
|
2015-08-20 00:24:47 +00:00
|
|
|
string = new_string;
|
2015-08-05 01:30:40 +00:00
|
|
|
}
|
2015-08-18 08:32:54 +00:00
|
|
|
string[length] = '\0';
|
2015-08-05 01:30:40 +00:00
|
|
|
return string;
|
|
|
|
}
|
2016-01-28 12:56:46 +00:00
|
|
|
|
|
|
|
char *read_line_buffer(FILE *file, char *string, size_t string_len) {
|
|
|
|
size_t length = 0;
|
|
|
|
if (!string) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
while (1) {
|
|
|
|
int c = getc(file);
|
|
|
|
if (c == EOF || c == '\n' || c == '\0') {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (c == '\r') {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
string[length++] = c;
|
|
|
|
if (string_len <= length) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (length + 1 == string_len) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
string[length] = '\0';
|
|
|
|
return string;
|
|
|
|
}
|