Mark McIntyre <ma**********@spamcop.netwrites:
broli wrote:
>I wrote a simple program that copies input to output but this is done
by using fread and fwrite.
#include<stdio.h>
int main(void)
{
FILE *fp;
int foo[10];
int a[10];
fread(a, sizeof(int), 10, stdin);
This fread reads 10 lots of sizeof(int) bytes from stdin.
Since sizeof(int) is two on your system ,you read 20 bytes.
I don't think we can conclude that sizeof(int) is 2 on his system. It
could well be 4. It's 4 on my system, and I get results that *look*
very much like his.
The fread call only reads 5 ints (20 bytes); since he doesn't check
the returned value, the failure is silent.
The fwrite call writes all 40 bytes of the buffer, but everything
after the data read into the buffer is likely (but by no means
certain) to be null characters, which are likely (but by no means
certain) to have no visible effect on output. Displaying the values
returned by the fread and fwrite calls, and viewing the output in some
other manner (on Unix, by piping it through "cat -A") will show what's
going on.
fread does not scan for objects. It reads blocks of data.
That's an odd use of the word "objects".
fread reads data, typically binary data, as a sequence of bytes. It
*can* be used to read text data (you'll even get the proper new-line
conversions if the file is in text mode), but it's clumsy, since it
doesn't care about line boundaries.
You want the fgets followed by sscanf. Don't forget to check the
result of the functions
There are drawbacks to the fgets/sscanf approach, but it's a good
start -- certainly better in this context than fread/fwrite.
--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"