2018-04-01 14:21:12 -07:00
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
2018-04-01 23:24:14 -07:00
|
|
|
char *loadfile(const char *fname, unsigned int *s) {
|
2018-04-01 14:21:12 -07:00
|
|
|
FILE *f = fopen(fname, "rb");
|
|
|
|
unsigned int size = 0; // number of elements to buffer;
|
|
|
|
unsigned int rcnt = 0; // number of char's read by fread(...)
|
|
|
|
if (f == NULL) {
|
|
|
|
perror("Error 1: ");
|
2018-04-01 18:32:54 -07:00
|
|
|
return NULL;
|
2018-04-01 14:21:12 -07:00
|
|
|
}
|
2018-04-09 20:21:56 -07:00
|
|
|
// this method of determining file size works up to 2 GB.
|
2018-04-01 14:21:12 -07:00
|
|
|
fseek(f, 0, SEEK_END);
|
|
|
|
size = ftell(f);
|
|
|
|
rewind(f);
|
2018-04-01 18:32:54 -07:00
|
|
|
char *buf = (char*)malloc(sizeof(char) * size);
|
2018-04-01 17:19:39 -07:00
|
|
|
if (buf == NULL) {
|
2018-04-01 14:21:12 -07:00
|
|
|
perror("Error 2: ");
|
2018-04-01 17:19:39 -07:00
|
|
|
free(buf);
|
2018-04-01 18:32:54 -07:00
|
|
|
return NULL;
|
2018-04-01 14:21:12 -07:00
|
|
|
}
|
2018-04-01 17:19:39 -07:00
|
|
|
rcnt = fread(buf, sizeof(char), size, f);
|
2018-04-01 14:21:12 -07:00
|
|
|
if (rcnt < size) {
|
|
|
|
perror("Error 3: ");
|
2018-04-01 17:19:39 -07:00
|
|
|
free(buf);
|
2018-04-01 18:32:54 -07:00
|
|
|
return NULL;
|
2018-04-01 14:21:12 -07:00
|
|
|
}
|
|
|
|
fclose(f);
|
2018-04-01 19:14:58 -07:00
|
|
|
*s = rcnt;
|
2018-04-01 18:32:54 -07:00
|
|
|
return buf;
|
2018-04-01 14:21:12 -07:00
|
|
|
}
|
|
|
|
|
2018-04-06 16:07:35 -07:00
|
|
|
void write(const char *filename,
|
|
|
|
const char* t,
|
|
|
|
unsigned int size) {
|
|
|
|
if (filename == NULL) {
|
|
|
|
return;
|
2018-04-01 14:21:12 -07:00
|
|
|
}
|
2018-04-06 16:07:35 -07:00
|
|
|
unsigned int written = 0;
|
|
|
|
FILE *out = fopen(filename, "wb");
|
|
|
|
if (out != NULL) {
|
|
|
|
written = fwrite(t, sizeof(unsigned char), size, out);
|
|
|
|
fclose(out);
|
|
|
|
if (written == 0) {
|
2018-04-18 02:12:06 -07:00
|
|
|
perror("write error");
|
2018-04-19 05:58:35 -07:00
|
|
|
exit(4);
|
2018-04-06 16:07:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-04-06 14:42:52 -07:00
|
|
|
|
2018-04-18 00:14:11 -07:00
|
|
|
|
2018-04-18 02:12:06 -07:00
|
|
|
void append(const char *filename, const char *t, unsigned size) {
|
|
|
|
if (filename == NULL) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
unsigned int written = 0;
|
|
|
|
FILE *out = fopen(filename, "ab");
|
|
|
|
if (out != NULL) {
|
|
|
|
written = fwrite(t, sizeof(unsigned char), size, out);
|
|
|
|
fclose(out);
|
|
|
|
if (written == 0) {
|
|
|
|
perror("write error");
|
2018-04-19 05:58:35 -07:00
|
|
|
exit(4);
|
2018-04-18 02:12:06 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|