3 ms·
Any explanation for this solution: (I'm not overly familiar with C, and I'm very curious as to how it works) #include <stdio.h> #include <stdlib.h> #include <s
by Foy 14y ago
Any explanation for this solution:
(I'm not overly familiar with C, and I'm very curious as to how it works)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * fp=fopen("temp.dat","w+b");
int number=12346;
int divisor=3;
char * buf = malloc(number);
memset(buf,0,number);
fwrite(buf,number,1,fp);
rewind(fp);
int result=fread(buf,divisor,number,fp);
printf("%d / %d = %d", number, divisor, result);
free(buf);
fclose(fp);
return 0;
}
- verroq 14y agoWrite 12346 zeros into the file. Read the file back in blocks of size 3. fread returns number of blocks read.
- to3m 14y agofread and fwrite do their thing on N chunks of M bytes each, and fread returns the number of chunks that it managed to read. So the write writes 1 chunk of `number' byte each, then the read reads `number' chunks of `divisor' bytes each (obviously this value will be larger than the number of bytes in the file). And by returning the number of `divisor'-byte chunks needed to read a file of `number' bytes in size, you get your answer. This just goes to prove that fread and fwrite are the biggest pile of crap.
- pif 14y agoHe writes "number" bytes into a temporary file and then, starting from the beginning, re-reads them in blocks of "divisor" bytes each. "fread" returns the number of full blocks read from the stream.