mirror of
https://github.com/labwc/labwc.git
synced 2025-10-29 05:40:24 -04:00
Add a BUF_INIT macro, which makes it easier to initialize a struct buf to an empty string (without a heap allocation). Add buf_move() to move the contents of one struct buf to another (the source is reset to BUF_INIT, analogous to C++ move-assignment). Use buf_reset() instead of directly calling `free(s->buf)` since the internal buf may not always be allocated by malloc() now.
36 lines
629 B
C
36 lines
629 B
C
// SPDX-License-Identifier: GPL-2.0-only
|
|
/*
|
|
* Read file into memory
|
|
*
|
|
* Copyright Johan Malm 2020
|
|
*/
|
|
|
|
#define _POSIX_C_SOURCE 200809L
|
|
#include "common/grab-file.h"
|
|
#include "common/buf.h"
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
struct buf
|
|
grab_file(const char *filename)
|
|
{
|
|
char *line = NULL;
|
|
size_t len = 0;
|
|
FILE *stream = fopen(filename, "r");
|
|
if (!stream) {
|
|
return BUF_INIT;
|
|
}
|
|
struct buf buffer = BUF_INIT;
|
|
while ((getline(&line, &len, stream) != -1)) {
|
|
char *p = strrchr(line, '\n');
|
|
if (p) {
|
|
*p = '\0';
|
|
}
|
|
buf_add(&buffer, line);
|
|
}
|
|
free(line);
|
|
fclose(stream);
|
|
return buffer;
|
|
}
|