0
votes

Simply problem, but slightly weird because of requirements.

Basically, I am trying to prevent buffer overflow when I am reading in file use file I/O because I am reading the file with a buffer size of 32. I feel like this should have been answered somewhere, but for the life of me my searching is not turning it up.

A simplified version of my code is here:

#include <stdio.h>                
#include <string.h>               
#define BUFFER_SIZE 32              
 
int main(int argc, char *argv[]) {
    FILE * read_file;
       
    char buffer[BUFFER_SIZE];
    read_file = fopen("test.txt","r");
    
    size_t num_rec = BUFFER_SIZE;
    while(fread(buffer, 1,num_rec, read_file) > 0) {
        printf("%s", buffer);
    }
    fclose(read_file);
    
    return 0;
}

Say I am trying to read a test.txt that has the contents:

This is a test file. 
The file is a test. 
I am having an overflow problem.
My C is not the best.

I get a output like this:

This is a test file.                                                                                                                                                               
The file is a test.                                                                                                                                                                
I am having an overflow problem.                                                                                                                                                   
My C is not the best.w problem.                                                                                                                                                    
My C is not the best

I understand that the simplest way of solving this is reading in 1 char at a time not 32, however, is there a way to solve this while still reading in 32 chars at a time?

2
printf expects a null terminated string, but you never arranged for buffer to be null terminated. - Nate Eldredge

2 Answers

2
votes

The fread() function reads binary data and doesn't add null bytes. You need to tell printf() how many bytes to print, which should be the number returned by fread().

size_t nbytes;
while((nbytes = fread(buffer, 1, num_rec, read_file)) > 0)
    printf("%.*s", (int)nbytes, buffer);

Note that fread() returns a size_t, but the .* operation in printf() requires an int; hence the cast (though it would be possible to save the value from fread() in an int and use that without the cast).

2
votes

The following saves the return value of fread then uses it to printf the characters that have been read, and no more than that.

    size_t read_bytes;
    while((read_bytes = fread(buffer, 1,num_rec, read_file)) > 0) {
        printf("%.*s", (int)read_bytes, buffer);
    }