<commit_before>#include "buffer.h"

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

Buffer *new_buffer(void)
{
	Buffer *buffer = calloc(1, sizeof(Buffer));
	if (!buffer) return NULL;
	buffer->text = new_document();
	if (!buffer->text) {
		free(buffer);
		return NULL;
	}
	return buffer;
}

void delete_buffer(Buffer *buffer)
{
	delete_text(buffer->text);
	free(buffer->filename);
	free(buffer);
}

int attach_file(Buffer *buffer, char *filename)
{
	FILE *fp;
	char buf[20];
	size_t nread;
	int ret;
	long file_size;
	char *old_filename = buffer->filename;
	buffer->filename = calloc(1, strlen(filename) + 1);
	if (!buffer->filename) {
		buffer->filename = old_filename;
		return -1;
	}
	strcpy(buffer->filename, filename);
	if (old_filename) {
		free(old_filename);
	}

	fp = fopen(filename, "r");
	if (!fp)
		return -1;

	fseek(fp, 0L, SEEK_END);
	file_size = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	resize_gap(buffer->text, file_size);

	while ((nread = fread(buf, 1, sizeof buf, fp)) > 0)
		add_string(buffer->text, buf, nread);

	ret = fclose(fp);
	if (ret) return -1;

	move_cursor_to_beg(buffer->text);

	return 0;
}<commit_msg>Check for error conditions when reading files<commit_after>#include "buffer.h"

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

Buffer *new_buffer(void)
{
	Buffer *buffer = calloc(1, sizeof(Buffer));
	if (!buffer) return NULL;
	buffer->text = new_document();
	if (!buffer->text) {
		free(buffer);
		return NULL;
	}
	return buffer;
}

void delete_buffer(Buffer *buffer)
{
	delete_text(buffer->text);
	free(buffer->filename);
	free(buffer);
}

int attach_file(Buffer *buffer, char *filename)
{
	FILE *fp;
	char buf[20];
	size_t nread;
	int ret;
	long file_size;
	char *old_filename = buffer->filename;
	buffer->filename = calloc(1, strlen(filename) + 1);
	if (!buffer->filename) {
		buffer->filename = old_filename;
		return -1;
	}
	strcpy(buffer->filename, filename);
	if (old_filename) {
		free(old_filename);
	}

	fp = fopen(filename, "r");
	if (!fp)
		return -1;

	fseek(fp, 0L, SEEK_END);
	file_size = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	resize_gap(buffer->text, file_size);

	while ((nread = fread(buf, 1, sizeof buf, fp)) > 0 && !ferror(fp))
		add_string(buffer->text, buf, nread);

	if (ferror(fp)) {
		fclose(fp);
		return -1;
	}

	ret = fclose(fp);
	if (ret) return -1;

	move_cursor_to_beg(buffer->text);

	return 0;
}
{'fraction_non_alphanumeric': 0.16771488469601678, 'fraction_numerical': 0.011320754716981131, 'mean_word_length': 4.627358490566038, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 35, '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': '543312', 'n_tokens_mistral': 994, 'n_tokens_neox': 937, 'n_words': 218}