2021-03-08 16:59:27 -05:00
|
|
|
#include <assert.h> /* assert */
|
|
|
|
#include <stdio.h> /* FILE* */
|
|
|
|
#include <stdlib.h> /* malloc, free */
|
2021-03-11 17:23:43 -05:00
|
|
|
#include <unistd.h> /* unlink */
|
2021-03-08 16:59:27 -05:00
|
|
|
|
2021-03-08 23:16:14 -05:00
|
|
|
#include "io.h"
|
|
|
|
|
2021-03-08 16:59:27 -05:00
|
|
|
/* <https://rosettacode.org/wiki/Read_entire_file#C> */
|
2021-03-11 12:48:15 -05:00
|
|
|
char *file_read(const char *filename, size_t *readSize) {
|
2021-03-08 16:59:27 -05:00
|
|
|
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);
|
2021-03-08 23:16:14 -05:00
|
|
|
if (size > 0)
|
2021-03-11 17:23:43 -05:00
|
|
|
buffer = (char *)malloc((size_t)size);
|
2021-03-08 16:59:27 -05:00
|
|
|
if (buffer != NULL) {
|
|
|
|
assert(buffer != NULL);
|
2021-03-08 23:16:14 -05:00
|
|
|
nread = fread(buffer, 1, (size_t)size, fh);
|
2021-03-08 16:59:27 -05:00
|
|
|
fclose(fh);
|
|
|
|
fh = NULL;
|
|
|
|
if (size != (long)nread) {
|
|
|
|
free(buffer);
|
|
|
|
buffer = NULL;
|
|
|
|
}
|
|
|
|
assert(size == (long)nread);
|
2021-03-11 12:48:15 -05:00
|
|
|
if (NULL != readSize) {
|
|
|
|
*readSize = nread;
|
|
|
|
}
|
2021-03-08 16:59:27 -05:00
|
|
|
}
|
|
|
|
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;
|
|
|
|
}
|
2021-03-11 17:23:43 -05:00
|
|
|
|
|
|
|
int copy_file(const char *srcname, const char *dstname) {
|
|
|
|
int rc;
|
|
|
|
char *buf;
|
|
|
|
size_t nread, nwrite;
|
|
|
|
rc = -1;
|
|
|
|
buf = file_read(srcname, &nread);
|
|
|
|
if (buf) {
|
|
|
|
nwrite = file_write(dstname, buf, nread);
|
|
|
|
if (nread != nwrite) {
|
|
|
|
fprintf(stderr, "Incorrect write size (%ld != %ld)\n", nread, nwrite);
|
|
|
|
unlink(dstname);
|
|
|
|
}
|
|
|
|
assert(nread == nwrite);
|
|
|
|
free(buf);
|
|
|
|
rc = 0;
|
|
|
|
}
|
|
|
|
return rc;
|
|
|
|
}
|