mirror of
https://notabug.org/scuti/lib3ddevil1
synced 2024-11-21 21:32:58 +05:30
69 lines
1.6 KiB
C
69 lines
1.6 KiB
C
#include <stdbool.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
char *loadfile(const char *fname, unsigned int *s) {
|
|
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: ");
|
|
return NULL;
|
|
}
|
|
// this method of determining file size works up to 2 GB.
|
|
fseek(f, 0, SEEK_END);
|
|
size = ftell(f);
|
|
rewind(f);
|
|
char *buf = (char*)malloc(sizeof(char) * size);
|
|
if (buf == NULL) {
|
|
perror("Error 2: ");
|
|
free(buf);
|
|
return NULL;
|
|
}
|
|
rcnt = fread(buf, sizeof(char), size, f);
|
|
if (rcnt < size) {
|
|
perror("Error 3: ");
|
|
free(buf);
|
|
return NULL;
|
|
}
|
|
fclose(f);
|
|
*s = rcnt;
|
|
return buf;
|
|
}
|
|
|
|
void write(const char *filename,
|
|
const char* t,
|
|
unsigned int size) {
|
|
if (filename == NULL) {
|
|
return;
|
|
}
|
|
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) {
|
|
perror("write error");
|
|
exit(4);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
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");
|
|
exit(4);
|
|
}
|
|
}
|
|
}
|