fread/fwrite

B

billcun

In said:
I want to be sure what these two functions are for.

They are for reading/writing chunks of data to/from a stream.
To copy for example 1 2048 size bytes block at a time?

You could use them for that purpose.  They can also work with other
block sizes.
I usually use fgetc and fputc.

It can be more efficient to work with whole blocks at once, rather than
one character at a time.
But I would please like for someone if they would to show me an example
of these functions.

Here's a sample using fread to read up to 1000 characters from a file:

  char buf[1000];
  FILE *fp;
  fp = fopen("filename.txt", "r");
  bytes_read = fread(buf, 1, sizeof(buf) - 1, fp);
  buf[bytes_read] = 0;
  fclose(fp);

Here's a sample using fwrite to write a fixed message to a file:

  char *message = "Hello earthlings.";
  FILE *fp;
  fp = fopen("message.txt", "w");
  bytes_written = fwrite(message, 1, strlen(message), fp);
  fclose(fp);

The first argument to fread/fwrite is a pointer to the buffer being read
or written.

The second argument is the size of each element being read/written.  In
these examples we're writing characters, so the size is 1.  If we were
writing other objects, we would use the size of those objects.

The third argument is the number of elements to be read/written.

The fourth argument is the stream to which the elements are to be
read/written.

The return value is the number of elements actually read/written, which
may be less than the number you requested, in which case you'll have to
keep calling fread/fwrite until all the data gets processed.
Thank you very much John. I understand the strlen because we are
dealing with a string. But what the -1 in your code for?

B
 
J

John Gordon

In said:
Thank you very much John. I understand the strlen because we are
dealing with a string. But what the -1 in your code for?

I assume you're asking about this line:

bytes_read = fread(buf, 1, sizeof(buf) - 1, fp);

The -1 allows room for a terminating null byte at the end of buf, because
buf is intended to be used as a string.

If we didn't intend to use buf as a string, the -1 would not be needed.
 
B

billcun

I assume you're asking about this line:

    bytes_read = fread(buf, 1, sizeof(buf) - 1, fp);

The -1 allows room for a terminating null byte at the end of buf, because
buf is intended to be used as a string.

If we didn't intend to use buf as a string, the -1 would not be needed.

Thanks for your explaination John. Yes that was what I was talking
about. And your patience.
 
B

billcun

On Jun 19, 4:17 pm, (e-mail address removed) wrote: [...]
I can't decide whether he's a) simply incapable of learning or b) a
subtle troll pretending to be a), though I'm beginning to lean towards
b). Either way, I don't believe there is much point attempting to
teach him.
   Things are not *taught* on clc. You do not learn anything.

I have been programming in C for about 29 years, and I've learned things
about C in this group.  True, most people would probably consider those
things "obscure", such as why my attempt to #define the name of a header
file wasn't working:

     Compile with "-DMYHEADER=myheader.h"
     ...
     #include <MYHEADER>

because of the way "<MYHEADER>" is parsed.  Instead, I can use this, which
does work:

     Compile with "-DMYHEADER='<myheader.h>'"
     ...
     #include MYHEADER

Then there are techniques that are "obvious" in today's C world, but which
weren't consistently available in K&R1 days, and so I often use "antiquated"
means of doing things, simply because that's the way I learned how to do
them.  Seeing things mentioned here reminds me at times that there are
better ways of doing things.

(I learned C along with the need to write with multiple platforms in mind..
In some ways, starting with the need to support both big-endian 32-bit Unix
systems and little-endian 16-bit MS-DOS systems taught me a lot about
portability.  I definitely never had the "all the world's a VAX" attitude.)
It is a C social group.

At times, yes.
I can count on one hand what I've been *taught* on clc.

Perhaps the problem isn't the teacher?

There is a simple and straight foreward way to put things. Long drawn
out explainations to hobbyists about macro expansion (I know nothing
about) from a PhD's doctoral really don't help. I'm not a computer
scientist.
I rarely see "GIYF".

I see it every other response post. To my postings. Also on another
note I have not seen this told to others but I have been in a hurry
and mispelled simple words that are readable and been mocked and
"quickley dropped from tutoring." As I said before I believe there are
alot of serious programmers on this group computer scientists.
Patience is not common.

And the "I don't do homework" responses are to people
who don't want to be taught, but rather want to be given the answer

"Given the answer" What does that mean? I don't do homework for
school. I try to learn. I see alot of unreadable code that when shown
to others who are patient. I've been able to grasp.

, often
to a "problem" that is a typical homework-type assignment.


No comment.
I think everyone's in a hurry to get back to the lab and write
commercial software.

B
 
B

BartC

I see it every other response post. To my postings. Also on another
note I have not seen this told to others but I have been in a hurry
and mispelled simple words that are readable and been mocked and
"quickley dropped from tutoring." As I said before I believe there are
alot of serious programmers on this group computer scientists.
Patience is not common.

The problem is you've been asking the same questions repeatedly over a
decade or so, and never seem to learn.

Up to a point, any answers given are sometimes useful to other readers of
the group, but you can understand that people can lose patience.
 
B

Bill Cunningham

On Jun 19, 4:17 pm, (e-mail address removed) wrote: [...]
I can't decide whether he's a) simply incapable of learning or b) a
subtle troll pretending to be a), though I'm beginning to lean towards
b). Either way, I don't believe there is much point attempting to
teach him.
   Things are not *taught* on clc. You do not learn anything.

I have been programming in C for about 29 years, and I've learned things
about C in this group.  True, most people would probably consider those
things "obscure", such as why my attempt to #define the name of a header
file wasn't working:

     Compile with "-DMYHEADER=myheader.h"
     ...
     #include <MYHEADER>

because of the way "<MYHEADER>" is parsed.  Instead, I can use this, which
does work:

     Compile with "-DMYHEADER='<myheader.h>'"
     ...
     #include MYHEADER

I think a typical ask to me for a question like that is "see
comp.compilers..." With an impression to me like "I gotta go...The lab
is waiting..."
Then there are techniques that are "obvious" in today's C world, but which
weren't consistently available in K&R1 days, and so I often use "antiquated"
means of doing things, simply because that's the way I learned how to do
them.  Seeing things mentioned here reminds me at times that there are
better ways of doing things.

As for techniques that are obvious in the C world I don't know because
I am not in the C world. Nor am I a computer scientist or doing
homework to become one.
 
I

Ian Collins

I see it every other response post. To my postings.

As others have pointed out, you have been asking the same or similar
questions here for many years.

Your original question on this thread could easily have been answered
with a quick search. Quite often the search results for your questions
include the thread from the previous time(s) you asked it!
 
B

Bill Cunningham

As others have pointed out, you have been asking the same or similar
questions here for many years.

Your original question on this thread could easily have been answered
with a quick search.  Quite often the search results for your questions
include the thread from the previous time(s) you asked it!

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.

B
 
B

Bill Cunningham

The first hit I get for fread is

http://www.cplusplus.com/reference/clibrary/cstdio/fread/

which has a clear explanation and example.

The first hit for "c fread example" also has a simple example.

I'm sure there are plenty more.
<cut example code>

#include <stdio.h>
#include <stdlib.h>

int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}


Below is not really clear to me. I haven't got to fseek yet

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);

Why is there a cast above when returns a generic pointer?

if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

/* the whole file is now loaded in the memory buffer. */

// terminate
fclose (pFile);
free (buffer);
return 0;
}

I only googled "man fread" and expected an example there.
I wanted and example with fwrite too.
 
I

Ian Collins

<cut example code>

#include<stdio.h>
#include<stdlib.h>

int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}


Below is not really clear to me. I haven't got to fseek yet

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);

Why is there a cast above when returns a generic pointer?

So it will compile as C++ (note the name of the site!).
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

/* the whole file is now loaded in the memory buffer. */

// terminate
fclose (pFile);
free (buffer);
return 0;
}

I only googled "man fread" and expected an example there.
I wanted and example with fwrite too.

Try improving your google searches.
 
B

Ben Bacarisse

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>
 
B

Bill Cunningham

 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-dee4a63d1...@f63g2000hsf.googlegroups.com>

OK I will cut and paste and study this. I was thinking of a do{}
while() approach.
 
B

Ben Bacarisse

Bill Cunningham said:
On Jun 20, 8:30 pm, Ben Bacarisse <[email protected]> wrote:

OK I will cut and paste and study this. I was thinking of a do{}
while() approach.

Well that's progress. Nick Keighley re-wrote the example to get rind of
a do ... while() because it confused you four years ago.
 
G

Guest

Things are not *taught* on clc. You do not learn anything.

*you* might not. It's a technical news group. if you ask a technical question
it's assumed you are interested in the answer! So you're just here to wasteour time?

It is a C
social group. I can count on one hand what I've been *taught* on clc.

that's because you're a cretin
If you want to learn something on clc the response is generally...
"GIYF" or "I don't do homework." You do not learn C here. You talk
about it or your experience with C. I've learned more about writing C
on private mail groups in 1 month more than years on clc.

I don't believe you've learnt anything
 
G

Guest

There is a simple and straight foreward way to put things. Long drawn
out explainations to hobbyists about macro expansion (I know nothing
about) from a PhD's doctoral really don't help. I'm not a computer
scientist.

seems like tails we lose heads you win. If we give short answers we're impatient and long answers we're showing off our PhDs.
I see it every other response post.

that's because you ask very basic questions that would be better answered by reading a basic tutorial. For ****'s sake you failed to recognise a simple array access in this very thread!
To my postings. Also on another
note I have not seen this told to others but I have been in a hurry
and mispelled simple words that are readable and been mocked and
"quickley dropped from tutoring."

I don't mock people for mispellings and typos (there's a good reason for that). But to answer question you have to understand it. And you mess up terminology, ask questions you didn't mean to ask (see this thread) and generally play fast and loose with the laws of english language and basic logic.

programmer is disiplined thought. you appear to unable to think or to organise yourself.
As I said before I believe there are
alot of serious programmers on this group computer scientists.

what language is *that* in.
Patience is not common.

you are shown far too much patience

at one time I had a list of responses for you. Number one was "work out what you are trying to do". you nearly always fail on that one. So why are youposting here? For fun?

<snip>
 
T

tom st denis

 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.

I learned how to use fread/fwrite while using Turbo C++ 1.01 [or
whatever the heck it was] which came free with a copy of "Type and
learn C" that I got when I was 10 [20 some odd years ago...]

Are you saying you're not as smart as a ten year old?

Tom
 
J

James Kuyper

I've got Bill Cunningham killfiled, but when I saw his comments quoted
by other people I felt I had to respond. Because he's on my killfile, I
can't respond to his message directly, so this will be marked as if it's
a response to Johannes's Bauer's message. Sorry for the mis-attribution.

Wow. Keep up the good work if it works for you. I have garnered
questions from tutorials such as on linked lists. I brought some
things up here and received numerous responses. The main one is "GIYF"
and then "Do your own homework" and "try comp.programming or another
NG"(concerning linked lists) I have *NEVER* got a good explanation. ...

You've received lots of good explanations over the past decade. People
with a wide variety of explanatory styles have done their best to
explain things in a way that you might be able to understand, but you've
never shown any sign of understanding any of them.

My own style is very verbose, detailed, and pedantic; for some people
that works, others find it either confusing or off-putting. I'm
disappointed, but not surprised, when any particular person fails to
understand any particular point I'm trying to make. But no one seems to
have a style that works with you.
... At
best some clues or told to read C FAQs. clc is a very rude and blunt
NG and that's its nature I have been warned and I can handle that. I
have found personally Beej's guides to be very informative and learned
about dereferencing too. I am beginning to learn pointers and write in
structs and pointer members. *No* thanks to clc but another source. ...

What's particularly depressing is your periodic claims that you have
learned something about C, almost always immediately followed by
statements that make it quite clear that you have not. If you have
indeed found someone who does know how to explain things in a way that
you can understand, then I'm happy for you - but based upon previous
experience I suspect you're deluding yourself again.
... In
a month very helpful people took me step by step. My suspicion is that
clc is full or professional programmers that don't have the time or
patience to work with amateurs like me anyway and there may be other

A large fraction of the people who post here regularly do so precisely
because we enjoy explaining how to use C to people who are eager to
learn it, even amateurs and hobbyists. Dozens, possibly hundreds of
people have been very patient with you for years. The problem is that,
sooner or later, you exhaust everyone's patience, by failing to
understand even the very clearest explanations of even the simplest
concepts, and by seldom ever following any of the good advice you've
been given.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

fread/fwrite 2 18
fread/fwrite 34
H&S fread/fwrite 7
streams binary and text 4
fgetc() vs. fread() 8
Can not read VCD file in Linux 8
stream functions 23
strdup + fread = fail? 5

Members online

Forum statistics

Threads
474,079
Messages
2,570,573
Members
47,205
Latest member
ElwoodDurh

Latest Threads

Top