<commit_before>#include "buffer.h"
#include "line.h"

#include <stdlib.h>
#include <string.h>

Buffer * buf_new(const char *name)
{
    Buffer *buf = calloc(1, sizeof(Buffer));
    if (name) {
        buf_read(buf, name);
        buf->name = strdup(name);
    }
    else {
        Line *l = line_new(NULL, 0);
        buf_pushback(buf, l);
        buf->line = l;
    }
    return buf;
}

void buf_free(Buffer *buf)
{
    buf_clear(buf);
    buf->next = buf->prev = NULL;
    free(buf->name);
    buf->name = '\0';
    free(buf);
}

bool buf_read(Buffer *buf, const char *name)
{
    buf_clear(buf);
    FILE *fp = fopen(name ?: buf->name, "r");
    if (fp) {
        char in[BUFSIZ];
        while (fgets(in, BUFSIZ, fp) != NULL) {
            Line *l = line_new(in, strlen(in) - 1);
            buf_pushback(buf, l);
        }
        buf->line = buf->beg;
        fclose(fp);
        return true;
    }
    return false;
}

bool buf_write(Buffer *buf, const char *name)
{
    FILE *fp = fopen(name ?: buf->name, "w");
    if (fp) {
        for (Line *l = buf->beg; l != NULL; l = l->next) {
            fprintf(fp, "%s\n", l->str);
        }
        fclose(fp);
        return true;<commit_msg>Fix segfault when opening a non-existent file in a new tab<commit_after>#include "buffer.h"
#include "line.h"

#include <stdlib.h>
#include <string.h>

Buffer * buf_new(const char *name)
{
    Buffer *buf = calloc(1, sizeof(Buffer));
    if (name)
        buf->name = strdup(name);
    buf_read(buf, name);
    return buf;
}

void buf_free(Buffer *buf)
{
    buf_clear(buf);
    buf->next = buf->prev = NULL;
    free(buf->name);
    buf->name = '\0';
    free(buf);
}

bool buf_read(Buffer *buf, const char *name)
{
    buf_clear(buf);
    FILE *fp = fopen(name ?: buf->name, "r");
    if (fp) {
        char in[BUFSIZ];
        while (fgets(in, BUFSIZ, fp) != NULL) {
            Line *l = line_new(in, strlen(in) - 1);
            buf_pushback(buf, l);
        }
        buf->line = buf->beg;
        fclose(fp);
        return true;
    }
    else {
        Line *l = line_new(NULL, 0);
        buf_pushback(buf, l);
        buf->line = l;
    }
    return false;
}

bool buf_write(Buffer *buf, const char *name)
{
    FILE *fp = fopen(name ?: buf->name, "w");
    if (fp) {
        for (Line *l = buf->beg; l != NULL; l = l->next) {
            fprintf(fp, "%s\n", l->str);
        }
        fclose(fp);
        return true;
{'fraction_non_alphanumeric': 0.1711340206185567, 'fraction_numerical': 0.0032989690721649486, 'mean_word_length': 2.063131313131313, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4503986', 'n_tokens_mistral': 920, 'n_tokens_neox': 908, 'n_words': 221}