Systems IO
Chunk Copy
A small buffer can copy a file in chunks until fread reaches the end.
Chunk Copy
chunk_copy.c
#include <stdio.h>
int main(void) {
int take = ;
char input[6] = {'a', 'b', 'c', 'd', 'e', 'f'};
char buffer[3];
int total = 0;
FILE *out = fopen("egtry_c17_source.bin", "wb");
fwrite(input, sizeof(input[0]), take, out);
fclose(out);
FILE *in = fopen("egtry_c17_source.bin", "rb");
int read = (int)fread(buffer, sizeof(buffer[0]), 3, in);
while (read > 0) {
total = total + read;
read = (int)fread(buffer, sizeof(buffer[0]), 3, in);
}
fclose(in);
remove("egtry_c17_source.bin");
printf("copied=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int take = ;
char input[6] = {'a', 'b', 'c', 'd', 'e', 'f'};
char buffer[3];
int total = 0;
FILE *out = fopen("egtry_c17_source.bin", "wb");
fwrite(input, sizeof(input[0]), take, out);
fclose(out);
FILE *in = fopen("egtry_c17_source.bin", "rb");
int read = (int)fread(buffer, sizeof(buffer[0]), 3, in);
while (read > 0) {
total = total + read;
read = (int)fread(buffer, sizeof(buffer[0]), 3, in);
}
fclose(in);
remove("egtry_c17_source.bin");
printf("copied=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int take = ;
char input[6] = {'a', 'b', 'c', 'd', 'e', 'f'};
char buffer[3];
int total = 0;
FILE *out = fopen("egtry_c17_source.bin", "wb");
fwrite(input, sizeof(input[0]), take, out);
fclose(out);
FILE *in = fopen("egtry_c17_source.bin", "rb");
int read = (int)fread(buffer, sizeof(buffer[0]), 3, in);
while (read > 0) {
total = total + read;
read = (int)fread(buffer, sizeof(buffer[0]), 3, in);
}
fclose(in);
remove("egtry_c17_source.bin");
printf("copied=%d\n", total);
return 0;
}
chunk
Each loop copies only the bytes that were actually read.
total bytes
Counting copied bytes verifies how much data moved through the buffer.