Bill Cunningham said:
I have read the man pages and googled them many times on fread and
fwrite. I have tried to go by that and failed. That's why I asked for
an example. In other places people readily showed me one with no
problem and I see now what I might have been doing wrong. The man
pages I looked at gave no example. Only parameters and a somewhat
cryptic mention of ferror and feof.
Here's an example (not my code):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buf [2048];
FILE *fp_in;
FILE *fp_out;
size_t ch_read;
if ((fp_in = fopen ("as.exe", "rb")) == NULL)
{
fprintf (stderr, "failed to open input file\n");
exit (EXIT_FAILURE);
}
if ((fp_out = fopen ("a.exe", "wb")) == NULL)
{
fprintf (stderr, "failed to open output file\n");
fclose (fp_in);
exit (EXIT_FAILURE);
}
ch_read = sizeof(buf);
while (ch_read == sizeof(buf))
{
ch_read = fread (buf, 1, sizeof(buf), fp_in);
if ((ch_read != sizeof(buf) && ferror(fp_in))
{
fprintf (stderr, "read error\n");
fclose (fp_in);
fclose (fp_out);
exit (EXIT_FAILURE);
}
if (fwrite (buf, 1, ch_read, fp_out) != ch_read)
{
fprintf (stderr, "write error\n");
fclose (fp_in);
fclose (fp_out);
exit (EXIT_FAILURE);
}
}
fclose (fp_in);
fclose (fp_out);
return 0;
}
It's Nick Keighley's example from 2008 -- simplified to remove a couple
of possibly confusing C idioms.
Source is Message-ID:
<657c2320-02d8-4413-9281-dee4a63d1583@f63g2000hsf.googlegroups.com>