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?
printfexpects a null terminated string, but you never arranged forbufferto be null terminated.