quote-bot/io.c
Bubblegumdrop 823330dde9 Insert, update, run script, run single query.
Most of the basic db functionality is in place now.

Changing print_col out for a user-supplied callback function might be a
cool idea.
2021-03-11 12:48:15 -05:00

60 lines
1.6 KiB
C

#include <assert.h> /* assert */
#include <stdio.h> /* FILE* */
#include <stdlib.h> /* malloc, free */
#include "io.h"
/* <https://rosettacode.org/wiki/Read_entire_file#C> */
char *file_read(const char *filename, size_t *readSize) {
char *buffer;
FILE *fh;
long size;
size_t nread;
assert(filename != NULL);
buffer = NULL;
fh = fopen(filename, "rb");
if (fh != NULL) {
fseek(fh, 0L, SEEK_END);
size = ftell(fh);
rewind(fh);
if (size > 0)
buffer = (char*)malloc((size_t)size);
if (buffer != NULL) {
assert(buffer != NULL);
nread = fread(buffer, 1, (size_t)size, fh);
fclose(fh);
fh = NULL;
if (size != (long)nread) {
free(buffer);
buffer = NULL;
}
assert(size == (long)nread);
if (NULL != readSize) {
*readSize = nread;
}
}
if (fh != NULL)
fclose(fh);
}
return buffer;
}
/* <https://www.rosettacode.org/wiki/Write_entire_file#C> */
size_t file_write(const char *fileName, const void *data, const size_t size) {
size_t numberBytesWritten = 0;
FILE *file;
assert(fileName != NULL);
assert(data != NULL);
assert(size > 0);
if (fileName != NULL && *fileName != '\0') {
file = fopen(fileName, "wb");
if (file != NULL) {
if (data != NULL) {
numberBytesWritten = fwrite(data, 1, size, file);
}
fclose(file);
}
}
return numberBytesWritten;
}