fread/fwrite

B

billcun

I want to be sure what these two functions are for. To copy for example 1 2048 size bytes block at a time? I usually use fgetc and fputc. But I would please like for someone if they would to show me an example of these functions.

THX
 
I

Ian Collins

I want to be sure what these two functions are for. To copy for example 1 2048 size bytes block at a time? I usually use fgetc and fputc. But I would please like for someone if they would to show me an example of these functions.

GIYF.
 
E

Eric Sosman

[... reformatted for line length ...]

I want to be sure what these two functions are for. To copy for
example 1 2048 size bytes block at a time? I usually use fgetc and
fputc. But I would please like for someone if they would to show me
an example of these functions.

They are "convenience functions" in the sense that you could
use repeated calls to fgetc/fputc (or getc/putc) to do pretty much
the same thing, transferring one byte per call. Since you transfer
(potentially) many bytes per call fread/fwrite could be a bit faster
than byte-at-a-time loops, but since most CPU's are millions of times
faster than most I/O devices any gains are unlikely to matter.

Here's a closer look at fread; fwrite is similar. First,
the declaration (slightly simplified):

size_t fread(
void * ptr, // where the input data will land
size_t size, // the size of one data element
size_t nmemb, // the number of elements to read
FILE * stream // the source from which they're read
);

The first likely point of bafflement is this "element" business.
fread/fwrite don't (necessarily) deal in single bytes, but in
units of (potentially) multi-byte items. To read an array of
forty-two something-or-others, you might use

fread(array, sizeof array[0], 42, stream);

If one something-or-other occupies ten bytes this will read 420
bytes; if it occupies just one byte this reads 42 bytes. The main
thing to keep in mind is that it reads 42 something-or-others of
`sizeof array[0]' bytes each.

Digression: Have you encountered other functions that deal
in "elements" of a specified size instead of directly with bytes?
Sure you have: There's qsort and bsearch, and for that matter calloc:
Each has a pair of arguments that specify an element size and an
element count. But be alert! Notice that qsort et al. describe their
elements the other way around: "count followed by size," whereas
fread/fwrite use "size followed by count." You've heard, perhaps,
of the "cathedral versus bazaar" approaches to system design? C's
library arose from the bazaar, and is occasionally, er, bizarre.

Okay, but what difference does it make? The number of bytes
transferred will be the product of the two arguments, and so will
be the same whichever way you specify them, right? Yes, but then
there's the matter of the value returned by the function: It's the
number of *elements* transferred, not the number of bytes. If you
read 42 10-byte elements or 10 42-byte elements you'll read 420
bytes either way, but one fread call will say "You got 42 elements"
and the other will say "You got 10 elements." Assuming you'll use
the returned value to figure out how many elements your program
should now digest, you'll want to keep size and count straight
lest you wind up reading 10 and trying to process 42, or reading
42 but processing only the first 10!

One problem with reporting the number of "elements" read or
written is that if you get an I/O error or end-of-file in the
middle of an element it's hard to determine exactly how far you
got. For example, if you try to read 42 10-byte elements and fread
says you got 16, you can't tell whether you got exactly 16, or 16
plus four bytes of a 17th and then EOF. A way around this is to use
one as your element size:

size_t bytes = fread(array, 1, 42 * sizeof array[0], stream);
size_t count = bytes / sizeof array[0];
size_t excess = bytes % sizeof array[0];
if (excess != 0) {
// Stopped in mid-element; something's strange.
// Maybe use feof(stream) and/or ferror(stream)
// and/or perror() to diagnose the problem.
...

I hope this helps.
 
J

John Gordon

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

billcun

On 6/18/2012 4:45 PM, (e-mail address removed) wrote:
 > [... reformatted for line length ...]
 >> I want to be sure what these two functions are for. To copy for

 > example 1 2048 size bytes block at a time? I usually use fgetc and> fputc. But I would please like for someone if they would to show me

 > an example of these functions.

     They are "convenience functions" in the sense that you could
use repeated calls to fgetc/fputc (or getc/putc) to do pretty much
the same thing, transferring one byte per call.  Since you transfer
(potentially) many bytes per call fread/fwrite could be a bit faster
than byte-at-a-time loops, but since most CPU's are millions of times
faster than most I/O devices any gains are unlikely to matter.

     Here's a closer look at fread; fwrite is similar.  First,
the declaration (slightly simplified):

        size_t fread(
            void * ptr,    // where the input data will land
            size_t size,   // the size of one data element
            size_t nmemb,  // the number of elements to read
            FILE * stream  // the source from which they'reread
        );

The first likely point of bafflement is this "element" business.
fread/fwrite don't (necessarily) deal in single bytes, but in
units of (potentially) multi-byte items.  To read an array of
forty-two something-or-others, you might use

        fread(array, sizeof array[0], 42, stream);


What does sizeof array[0] mean?
If one something-or-other occupies ten bytes this will read 420
bytes; if it occupies just one byte this reads 42 bytes.  The main
thing to keep in mind is that it reads 42 something-or-others of
`sizeof array[0]' bytes each.

     Digression: Have you encountered other functions that deal
in "elements" of a specified size instead of directly with bytes?
Sure you have: There's qsort and bsearch, and for that matter calloc:
Each has a pair of arguments that specify an element size and an
element count.  But be alert!  Notice that qsort et al. describe their
elements the other way around: "count followed by size," whereas
fread/fwrite use "size followed by count."  You've heard, perhaps,
of the "cathedral versus bazaar" approaches to system design?  C's
library arose from the bazaar, and is occasionally, er, bizarre.

     Okay, but what difference does it make?  The number of bytes
transferred will be the product of the two arguments, and so will
be the same whichever way you specify them, right?  Yes, but then
there's the matter of the value returned by the function: It's the
number of *elements* transferred, not the number of bytes.  If you
read 42 10-byte elements or 10 42-byte elements you'll read 420
bytes either way, but one fread call will say "You got 42 elements"
and the other will say "You got 10 elements."  Assuming you'll use
the returned value to figure out how many elements your program
should now digest, you'll want to keep size and count straight
lest you wind up reading 10 and trying to process 42, or reading
42 but processing only the first 10!

     One problem with reporting the number of "elements" read or
written is that if you get an I/O error or end-of-file in the
middle of an element it's hard to determine exactly how far you
got.  For example, if you try to read 42 10-byte elements and fread
says you got 16, you can't tell whether you got exactly 16, or 16
plus four bytes of a 17th and then EOF.  A way around this is to use
one as your element size:

        size_t bytes = fread(array, 1, 42 * sizeof array[0], stream);
        size_t count = bytes / sizeof array[0];
        size_t excess = bytes % sizeof array[0];
        if (excess != 0) {
            // Stopped in mid-element; something's strange.
            // Maybe use feof(stream) and/or ferror(stream)
            // and/or perror() to diagnose the problem.
            ...

     I hope this helps.
 
I

Ike Naar

What does sizeof array[0] mean?

You've asked this question before (e.g. on 2011-05-28), and received
several answers that explained the whole thing in every detail.
Haven't you learned anything from those answers?
 
E

Eric Sosman

[...]
What does sizeof array[0] mean?

It means "a positive number."

(An old story has Fred calling some friends at home but hearing
"Hello" from a very young voice. "Is your father there?" "No."
"Okay, is your mother there?" "No." Um. "Could you tell them
Fred called?" "I'm going out soon." "Okay, could you leave them
a note that Fred called?" "Okay. I'll get some paper ... Okay,
how do you spell Fred?" Yikes. "F-R-E-D, got it?" "Okay. How do
you make an F?")
 
B

billcun

On 6/18/2012 4:45 PM, (e-mail address removed) wrote:
 > [... reformatted for line length ...]
 >> I want to be sure what these two functions are for. To copy for

 > example 1 2048 size bytes block at a time? I usually use fgetc and> fputc. But I would please like for someone if they would to show me

 > an example of these functions.

     They are "convenience functions" in the sense that you could
use repeated calls to fgetc/fputc (or getc/putc) to do pretty much
the same thing, transferring one byte per call.  Since you transfer
(potentially) many bytes per call fread/fwrite could be a bit faster
than byte-at-a-time loops, but since most CPU's are millions of times
faster than most I/O devices any gains are unlikely to matter.

     Here's a closer look at fread; fwrite is similar.  First,
the declaration (slightly simplified):

        size_t fread(
            void * ptr,    // where the input data will land
            size_t size,   // the size of one data element
            size_t nmemb,  // the number of elements to read
            FILE * stream  // the source from which they'reread
        );

The first likely point of bafflement is this "element" business.
fread/fwrite don't (necessarily) deal in single bytes, but in
units of (potentially) multi-byte items.  To read an array of
forty-two something-or-others, you might use

        fread(array, sizeof array[0], 42, stream);

If one something-or-other occupies ten bytes this will read 420
bytes; if it occupies just one byte this reads 42 bytes.  The main
thing to keep in mind is that it reads 42 something-or-others of
`sizeof array[0]' bytes each.

     Digression: Have you encountered other functions that deal
in "elements" of a specified size instead of directly with bytes?
Sure you have: There's qsort and bsearch, and for that matter calloc:
Each has a pair of arguments that specify an element size and an
element count.  But be alert!  Notice that qsort et al. describe their
elements the other way around: "count followed by size," whereas
fread/fwrite use "size followed by count."  You've heard, perhaps,
of the "cathedral versus bazaar" approaches to system design?  C's
library arose from the bazaar, and is occasionally, er, bizarre.

     Okay, but what difference does it make?  The number of bytes
transferred will be the product of the two arguments, and so will
be the same whichever way you specify them, right?  Yes, but then
there's the matter of the value returned by the function: It's the
number of *elements* transferred, not the number of bytes.  If you
read 42 10-byte elements or 10 42-byte elements you'll read 420
bytes either way, but one fread call will say "You got 42 elements"
and the other will say "You got 10 elements."  Assuming you'll use
the returned value to figure out how many elements your program
should now digest, you'll want to keep size and count straight
lest you wind up reading 10 and trying to process 42, or reading
42 but processing only the first 10!

     One problem with reporting the number of "elements" read or
written is that if you get an I/O error or end-of-file in the
middle of an element it's hard to determine exactly how far you
got.  For example, if you try to read 42 10-byte elements and fread
says you got 16, you can't tell whether you got exactly 16, or 16
plus four bytes of a 17th and then EOF.  A way around this is to use
one as your element size:

        size_t bytes = fread(array, 1, 42 * sizeof array[0], stream);
        size_t count = bytes / sizeof array[0];
        size_t excess = bytes % sizeof array[0];
        if (excess != 0) {
            // Stopped in mid-element; something's strange.
            // Maybe use feof(stream) and/or ferror(stream)
            // and/or perror() to diagnose the problem.
            ...

     I hope this helps.
In a way it has because you've introduced me to something new, the
argv[0]. But I don't quite undestand how you would use it. It's so
hard for aspiring amateurs like me who love to code to keep up with
professionals. Would a size of 2048 bytes as a block work or crash
things?

Bill
 
E

Eric Sosman

[...]
I hope this helps.
In a way it has because you've introduced me to something new, the
argv[0]. [...]

Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.

(Light dawns on Marblehead): Are you "Bill Cunningham," by any
chance? If so, I've been well and truly taken in. I apologize to
the group for wasting bandwidth, and will update my filters.
 
G

Guest

On 6/18/2012 4:45 PM, (e-mail address removed) wrote:
 > [... reformatted for line length ...]
 >> I want to be sure what these two functions are for.

[ie. fread() and fwrite()]

fread reads a block of data fwrite writes one. Can't you find this on google?

[...]
But I would please like for someone if they would to show me
 > an example of these functions.

     They are "convenience functions" in the sense that you could
use repeated calls to fgetc/fputc (or getc/putc) to do pretty much
the same thing, transferring one byte per call.  Since you transfer
(potentially) many bytes per call fread/fwrite could be a bit faster
than byte-at-a-time loops, but since most CPU's are millions of times
faster than most I/O devices any gains are unlikely to matter.

     Here's a closer look at fread; fwrite is similar.  First,
the declaration (slightly simplified):

        size_t fread(
            void * ptr,    // where the input data willland
            size_t size,   // the size of one data element
            size_t nmemb,  // the number of elements to read
            FILE * stream  // the source from which they're read
        );

The first likely point of bafflement is this "element" business.
fread/fwrite don't (necessarily) deal in single bytes, but in
units of (potentially) multi-byte items.  To read an array of
forty-two something-or-others, you might use

        fread(array, sizeof array[0], 42, stream);

If one something-or-other occupies ten bytes this will read 420
bytes; if it occupies just one byte this reads 42 bytes.  The main
thing to keep in mind is that it reads 42 something-or-others of
`sizeof array[0]' bytes each.

     Digression: Have you encountered other functions that deal
in "elements" of a specified size instead of directly with bytes?
Sure you have: There's qsort and bsearch, and for that matter calloc:
Each has a pair of arguments that specify an element size and an
element count.  But be alert!  Notice that qsort et al. describe their
elements the other way around: "count followed by size," whereas
fread/fwrite use "size followed by count."  You've heard, perhaps,
of the "cathedral versus bazaar" approaches to system design?  C's
library arose from the bazaar, and is occasionally, er, bizarre.

     Okay, but what difference does it make?  The number of bytes
transferred will be the product of the two arguments, and so will
be the same whichever way you specify them, right?  Yes, but then
there's the matter of the value returned by the function: It's the
number of *elements* transferred, not the number of bytes.  If you
read 42 10-byte elements or 10 42-byte elements you'll read 420
bytes either way, but one fread call will say "You got 42 elements"
and the other will say "You got 10 elements."  Assuming you'll use
the returned value to figure out how many elements your program
should now digest, you'll want to keep size and count straight
lest you wind up reading 10 and trying to process 42, or reading
42 but processing only the first 10!

     One problem with reporting the number of "elements" read or
written is that if you get an I/O error or end-of-file in the
middle of an element it's hard to determine exactly how far you
got.  For example, if you try to read 42 10-byte elements and fread
says you got 16, you can't tell whether you got exactly 16, or 16
plus four bytes of a 17th and then EOF.  A way around this is to use
one as your element size:

        size_t bytes = fread(array, 1, 42 * sizeof array[0], stream);
        size_t count = bytes / sizeof array[0];
        size_t excess = bytes % sizeof array[0];
        if (excess != 0) {
            // Stopped in mid-element; something's strange.
            // Maybe use feof(stream) and/or ferror(stream)
            // and/or perror() to diagnose the problem.
            ...

     I hope this helps.
In a way it has because you've introduced me to something new, the
argv[0].
where?

But I don't quite undestand how you would use it.

did you read what he wrote?
It's so
hard for aspiring amateurs like me who love to code to keep up with
professionals. Would a size of 2048 bytes as a block work or crash
things?

why would it crash? Is 2048 bytes sensible for the data you're reading?
 
B

billcun

[...]
      I hope this helps.
   In a way it has because you've introduced me to something new, the
argv[0].  [...]

     Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.

Sorry. Typo. I meant array[0]
     (Light dawns on Marblehead): Are you "Bill Cunningham," by any
chance?

Yes. My ISP's newsserver isn't working for now. I'm going through
google groups for as long as I have to.

If so, I've been well and truly taken in.

If you say so.

 I apologize to
the group for wasting bandwidth, and will update my filters.

Very well
 
G

Guest

   In a way it has because you've introduced me to something new,the
argv[0].  [...]

     Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.

Sorry. Typo. I meant array[0]

in what sense is array[0] "new"? You must have seen an array indexed before!

int array [10];
int i;

for (i = 0; i < 10; i++)
printf ("%d ", array);

printf ("\n");

array[1] = 1;
array[0] = 0;

are you saying /this/ is new to you?! You have K&R go and read the section on arrays *again*.

<snip>
 
M

Mark Bluemel

did you read what he wrote?

Why would you expect Bill to do that? He's been around this group long
enough for any regular reader to have some idea of his modus operandi.

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.
 
J

James Kuyper

� �In a way it has because you've introduced me to something new, the
argv[0]. �[...]

� � �Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.

Sorry. Typo. I meant array[0]

in what sense is array[0] "new"? You must have seen an array indexed before!

Every occurrence of array[0] in the message he was responding to was as
an operand of a sizeof operator. I remain uncertain whether Bill is
legitimately incapable of understanding anything, or whether he's a
troll pretending to be such a person, However, if his learning
disabilities are legitimate, my guess is that he doesn't understand the
key role played by the sizeof operator in those expressions, and
therefore zeroed in on array[0] as "the" peculiar feature that renders
that code beyond his understanding. Based upon past experience, if he's
not a troll, every feature of that code is beyond his ability to
understand - there's nothing special about array[0] in that regard.
 
G

Guest

� �In a way it has because you've introduced me to something new, the
argv[0]. �[...]

� � �Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.

Sorry. Typo. I meant array[0]

in what sense is array[0] "new"? You must have seen an array indexed before!

Every occurrence of array[0] in the message he was responding to was as
an operand of a sizeof operator.

I know. But he didn't say "I don't understand what 'sizeof arry[0]'
means" did he? he tried twice but failed both times. His inabilty to
think clearly is one of his problems.
I remain uncertain whether Bill is
legitimately incapable of understanding anything, or whether he's a
troll pretending to be such a person, However, if his learning
disabilities are legitimate, my guess is that he doesn't understand the
key role played by the sizeof operator in those expressions, and
therefore zeroed in on array[0] as "the" peculiar feature that renders
that code beyond his understanding. Based upon past experience, if he's
not a troll, every feature of that code is beyond his ability to
understand - there's nothing special about array[0] in that regard.
 
T

tom st denis

On Tuesday, June 19, 2012 5:51:55 PM UTC+1, (unknown) wrote:
In a way it has because you've introduced me to something new, the
argv[0]. [...]
Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.
Sorry. Typo. I meant array[0]
in what sense is array[0] "new"? You must have seen an array indexed before!
Every occurrence of array[0] in the message he was responding to was as
an operand of a sizeof operator.

I know. But he didn't say "I don't understand what 'sizeof arry[0]'
means" did he? he tried twice but failed both times. His inabilty to
think clearly is one of his problems.

The fact that he's a troll too is one of his problems.

Tom
 
B

billcun

   In a way it has because you've introduced me to something new, the
argv[0].  [...]
     Since I never mentioned argv[0], nor even argv, it's hard to
discern the nature of the introduction.
Sorry. Typo. I meant array[0]

in what sense is array[0] "new"? You must have seen an array indexed before!

Oh Ok yes of course. Yes. It was mentioned this was any positive
number. I was confused for a minute. Yeah I know what your talking
about.
   int array [10];
   int i;

   for (i = 0; i < 10; i++)
      printf ("%d ", array);

   printf ("\n");

   array[1] = 1;
   array[0] = 0;

are you saying /this/ is new to you?! You have K&R go and read the section on arrays *again*.

<snip>
 
B

billcun

Why would you expect Bill to do that? He's been around this group long
enough for any regular reader to have some idea of his modus operandi.

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. It is a C
social group. I can count on one hand what I've been *taught* on clc.
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.

B
 
J

Johannes Bauer

Things are not *taught* on clc. You do not learn anything. It is a C
social group. I can count on one hand what I've been *taught* on clc.
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.

My clc-experience seems to differ greatly from yours. For every question
I've asked so far here I've promptly received numerous, very verbose and
detailled and competent responses that hit the nail right on the head.
Always with included references for further reading (i.e. not only THAT
something is the way it is, but also WHY and where I can read more about
it). I really like this newsgroup.

Best regards,
Johannes

--
Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
- Karl Kaos über Rüdiger Thomas in dsa <[email protected]>
 
B

billcun

My clc-experience seems to differ greatly from yours. For every question
I've asked so far here I've promptly received numerous, very verbose and
detailled and competent responses that hit the nail right on the head.
Always with included references for further reading (i.e. not only THAT
something is the way it is, but also WHY and where I can read more about
it). I really like this newsgroup.

Best regards,
Johannes

Hello John,

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. 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. 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
hobbyists here too. I code in C for fun. I mainly lurk and find my
experience to be somewhat if not particularly normal. Good Luck

B
 

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
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top