Copy a file in C
Last updated on
I have todo this so often, copy the contents of a file.
/* filecpy.c */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void
get_file_contents(
FILE *f,
char **out_buffer,
long *out_size)
{
if(!f) {
assert(!"no file given");
}
fseek(f, 0, SEEK_END);
long len = ftell(f);
fseek(f, 0, SEEK_SET);
if(out_size) {
*out_size = (len + 1);
}
if(out_buffer) {
char *buf = *out_buffer;
fread(buf, len, 1, f);
buf[len] = '\0';
}
}
int
main() {
FILE *f = fopen("filecpy.c", "rb");
if(!f) {
assert(!"Failed to open file");
return EXIT_FAILURE;
}
long len = 0;
get_file_contents(f, NULL, &len);
if(!len) {
assert(!"File has no size?");
return EXIT_FAILURE;
}
char *buffer = malloc(len);
if(!buffer) {
assert(!"Failed to allocate");
return EXIT_FAILURE;
}
get_file_contents(f, &buffer, NULL);
printf("size: %d\n%s\n", (int)len, buffer);
return EXIT_SUCCESS;
}
Compile and Run in C
cc filecpy.c && ./a.out
That will copy the file into memory then print it out.