2018-04-02 02:51:12 +05:30
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
2018-04-02 11:54:14 +05:30
|
|
|
char *loadfile(const char *fname, unsigned int *s) {
|
2018-04-02 02:51:12 +05:30
|
|
|
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-02 07:02:54 +05:30
|
|
|
return NULL;
|
2018-04-02 02:51:12 +05:30
|
|
|
}
|
2018-04-10 08:51:56 +05:30
|
|
|
// this method of determining file size works up to 2 GB.
|
2018-04-02 02:51:12 +05:30
|
|
|
fseek(f, 0, SEEK_END);
|
|
|
|
size = ftell(f);
|
|
|
|
rewind(f);
|
2018-04-02 07:02:54 +05:30
|
|
|
char *buf = (char*)malloc(sizeof(char) * size);
|
2018-04-02 05:49:39 +05:30
|
|
|
if (buf == NULL) {
|
2018-04-02 02:51:12 +05:30
|
|
|
perror("Error 2: ");
|
2018-04-02 05:49:39 +05:30
|
|
|
free(buf);
|
2018-04-02 07:02:54 +05:30
|
|
|
return NULL;
|
2018-04-02 02:51:12 +05:30
|
|
|
}
|
2018-04-02 05:49:39 +05:30
|
|
|
rcnt = fread(buf, sizeof(char), size, f);
|
2018-04-02 02:51:12 +05:30
|
|
|
if (rcnt < size) {
|
|
|
|
perror("Error 3: ");
|
2018-04-02 05:49:39 +05:30
|
|
|
free(buf);
|
2018-04-02 07:02:54 +05:30
|
|
|
return NULL;
|
2018-04-02 02:51:12 +05:30
|
|
|
}
|
|
|
|
fclose(f);
|
2018-04-02 07:44:58 +05:30
|
|
|
*s = rcnt;
|
2018-04-02 07:02:54 +05:30
|
|
|
return buf;
|
2018-04-02 02:51:12 +05:30
|
|
|
}
|
|
|
|
|
2018-04-07 04:37:35 +05:30
|
|
|
void write(const char *filename,
|
|
|
|
const char* t,
|
|
|
|
unsigned int size) {
|
|
|
|
if (filename == NULL) {
|
|
|
|
return;
|
2018-04-02 02:51:12 +05:30
|
|
|
}
|
2018-04-07 04:37:35 +05:30
|
|
|
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 14:42:06 +05:30
|
|
|
perror("write error");
|
2018-04-07 04:37:35 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-04-07 03:12:52 +05:30
|
|
|
|
2018-04-18 12:44:11 +05:30
|
|
|
|
2018-04-18 14:42:06 +05:30
|
|
|
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-18 15:36:48 +05:30
|
|
|
printf("wrote %x\n", written);
|
2018-04-18 14:42:06 +05:30
|
|
|
}
|
|
|
|
}
|