printf("%s", chunks);
expect chunks[]
to be a string. Strings have a null character at the end and fread(chunks, 1, sizeof chunks, f)
did not certainly read a '\0'
and form a string.
Write what was read (Best)
// printf("%s", chunks);
fwrite(chunks, 1, size, stdout);
Write what was read up to a '\0'
"%.*s"
writes a limited amount from a character array, stopping at the size
or when a '\0'
is detected.
// printf("%s", chunks);
printf("%.*s", size, chunks);
Append your own '\0'
This will perform like printf("%.*s", size, chunks)
.
char chunks[4 + 1]; // One bigger
int size;
do {
// memset(chunks,0,sizeof chunks - 1); // Not needed
size = fread(chunks, 1, sizeof chunks - 1, f);
if (size <= 0) break;
chunks[size] = '\0';
printf("%s", chunks);
} while (size == sizeof chunks - 1);
Avoid naked magic numbers
Use size_t
for array sizing.
#define CHUNK_SIZE 4
char chunks[CHUNK_SIZE];
size_t size;
size_t n = sizeof chunks/sizeof *chunks;
do {
size = fread(chunks, sizeof *chunks, n, f);
if (size <= 0) break;
fwrite(chunks, sizeof *chunks, size, stdout);
} while (size == sizeof chunks);