int main()
{
char buffer[100];
fread(buffer,1,4,stdin);
int i=0;
while(i<4)
{
printf ("%c,\n",buffer[i]);
i=i+1;
}
getch();
}
How the fread function will know,when to stop reading the input stream,what does the size and count elements signify,and how to manipulate size and count to get the maximum stream reading speed?
To print all bytes in an
int? Remember that anintis 32-bit, which is four bytes. Reading it into acharbuffer makes it easier to access those four bytes in theint.Edit: Little explanation of the
inttype…Lets say you have an
int:This is stored in 32 bits in the memory. As a single byte (
char) is 8 bits, there are four bytes to anint. Each byte in theintcan be accessed by using achararray or pointer:Now you can access those four separate bytes, and see their values:
The above will print (on a little-endian machine such as x86):
If you now change
someIntValueto the number1and print it out again, you will see this result:
Memory layout of an
intIf you have a variable of type
intstored in memory with the value0x12345678, it’s stored like this:8 bits ,----^---. | | +--------+--------+--------+--------+ |00111000|01010110|00110100|00010010| +--------+--------+--------+--------+ | | `-----------------v-----------------' | 32 bitsThis
intis the same as the four bytes (orchar)0x78,0x56,0x34and0x12.However if we change the
intto the number1then it’s stored like this:8 bits ,----^---. | | +--------+--------+--------+--------+ |00000000|00000000|00000000|00000001| +--------+--------+--------+--------+ | | `-----------------v-----------------' | 32 bitsThis
intis the same as the four bytes (orchar)0x00,0x00,0x00and0x01.So now you hopefully can see how reading as an
intand printing ascharwill display a different result from reading andintand printing it as anint.