1
1
mirror of https://github.com/swaywm/sway synced 2024-09-30 00:43:40 +02:00
sway/common/readline.c

89 lines
1.6 KiB
C
Raw Normal View History

#include "readline.h"
2016-12-15 23:08:56 +01:00
#include "log.h"
#include <stdlib.h>
#include <stdio.h>
char *read_line(FILE *file) {
2016-01-28 13:56:46 +01:00
size_t length = 0, size = 128;
char *string = malloc(size);
char lastChar = '\0';
if (!string) {
2018-01-05 22:32:51 +01:00
wlr_log(L_ERROR, "Unable to allocate memory for read_line");
return NULL;
}
while (1) {
int c = getc(file);
if (c == '\n' && lastChar == '\\'){
--length; // Ignore last character.
lastChar = '\0';
continue;
}
if (c == EOF || c == '\n' || c == '\0') {
break;
}
if (c == '\r') {
continue;
}
lastChar = c;
if (length == size) {
2015-08-20 02:24:47 +02:00
char *new_string = realloc(string, size *= 2);
if (!new_string) {
free(string);
2018-01-05 22:32:51 +01:00
wlr_log(L_ERROR, "Unable to allocate memory for read_line");
return NULL;
}
2015-08-20 02:24:47 +02:00
string = new_string;
}
string[length++] = c;
}
if (length + 1 == size) {
2015-08-20 02:24:47 +02:00
char *new_string = realloc(string, length + 1);
if (!new_string) {
free(string);
return NULL;
}
2015-08-20 02:24:47 +02:00
string = new_string;
}
string[length] = '\0';
return string;
}
2016-01-28 13:56:46 +01:00
char *peek_line(FILE *file, int offset) {
int pos = ftell(file);
char *line = NULL;
for (int i = 0; i <= offset; i++) {
free(line);
line = read_line(file);
if (!line) {
break;
}
}
fseek(file, pos, SEEK_SET);
return line;
}
2016-01-28 13:56:46 +01: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;
}