read_line(): Simplify by using getline()

This commit is contained in:
Michael Schupikov 2017-01-09 12:29:13 +01:00
parent f213180533
commit 22f37db15e
2 changed files with 37 additions and 48 deletions

View file

@ -1,51 +1,45 @@
#include "readline.h" #include <assert.h>
#include "log.h"
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *read_line(FILE *file) { #include "log.h"
size_t length = 0, size = 128; #include "readline.h"
char *string = malloc(size); #include "stringop.h"
char lastChar = '\0';
if (!string) { /***************************************************************************//**
sway_log(L_ERROR, "Unable to allocate memory for read_line"); *
return NULL; * \brief Read one line of the configuration file.
} *
while (1) { * \param file Pointer to the already open configuration file. If NULL is
int c = getc(file); * passed, no operation is performed.
if (c == '\n' && lastChar == '\\'){ *
--length; // Ignore last character. * \return String containing one single line from the configuration file.
lastChar = '\0'; * This string is not necessarily in the format how it is expected
continue; * for further processing of configuration commands. NULL is
} * returned in case of failure or if NULL is passed for 'file'.
if (c == EOF || c == '\n' || c == '\0') { *
break; ******************************************************************************/
} inline char* read_line(FILE* restrict const file) {
if (c == '\r') { char* line = NULL;
continue; if (file) {
} size_t line_length = 0u;
lastChar = c; const ssize_t bytes_read = getline(&line, &line_length, file);
if (length == size) { if (line) {
char *new_string = realloc(string, size *= 2); assert(line_length);
if (!new_string) { if (0 > bytes_read) {
free(string); free(line);
sway_log(L_ERROR, "Unable to allocate memory for read_line"); line = NULL;
return NULL; } else {
strip_whitespace(line);
if (line[0] == '#') {
free(line);
line = NULL;
}
} }
string = new_string;
} }
string[length++] = c;
} }
if (length + 1 == size) { return line;
char *new_string = realloc(string, length + 1);
if (!new_string) {
free(string);
return NULL;
}
string = new_string;
}
string[length] = '\0';
return string;
} }
char *read_line_buffer(FILE *file, char *string, size_t string_len) { char *read_line_buffer(FILE *file, char *string, size_t string_len) {

View file

@ -632,11 +632,6 @@ bool read_config(FILE *file, struct sway_config *config) {
continue; continue;
} }
line_number++; line_number++;
strip_whitespace(line);
if (line[0] == '#') {
free(line);
continue;
}
struct cmd_results *res; struct cmd_results *res;
if (block == CMD_BLOCK_COMMANDS) { if (block == CMD_BLOCK_COMMANDS) {
// Special case // Special case