This can be a good question for finding bugs.
No? Okay for beginners at least.
#define SIZE 4
int main(void){
int chars_read = 1;
char buffer[SIZE + 1] = {0};
setvbuf(stdin, (char *)NULL, _IOFBF, sizeof(buffer)-1);
while(chars_read){
chars_read = fread(buffer, sizeof('1'), SIZE, stdin);
printf("%d, %s\n", chars_read, buffer);
}
return 0;
}
Using the above code, I am trying to read from a file using redirection ./a.out < data. Contents of input file:
1line
2line
3line
4line
But I am not getting the expected output, rather some graphical characters are mixed in.
What is wrong?
Hint: (Courtesy Alok)
sizeof('1') == sizeof(int)- sizeof("1") == sizeof(char)*2
So, use 1 instead 🙂
Take a look at this post for buffered IO example using fread.
The type of
'1'isintin C, notchar, so you are readingSIZE*sizeof(int)bytes in eachfread. Ifsizeof(int)is greater than 1 (on most modern computers it is), then you are reading past the storage forbuffer. This is one of the places where C and C++ are different: in C, character literals are of typeint, in C++, they are of typechar.So, you need
chars_read = fread(buffer, 1, SIZE, stdin);becausesizeof(char)is 1 by definition.In fact, I would write your loop as:
To answer your another question,
'\0'is theint0, so{'\0'}and{0}are equivalent.For
setvbuf, my documentation says:Why are you commenting with
\\instead of//or/* */? 🙂Edit: Based upon your edit of the question,
sizeof("1")is wrong,sizeof(char)is correct.sizeof("1")is 2, because"1"is achararray containing two elements:'1'and0.