Chapter Contents |
Previous |
Next |
fread |
Portability: | ISO/ANSI C conforming, UNIX compatible |
SYNOPSIS | |
DESCRIPTION | |
RETURN VALUE | |
CAUTION | |
DIAGNOSTICS | |
PORTABILITY | |
IMPLEMENTATION | |
EXAMPLE | |
RELATED FUNCTIONS | |
SEE ALSO |
SYNOPSIS |
#include <stdio.h> size_t fread(void *ptr, size_t size, size_t count, FILE *f);
DESCRIPTION |
fread
reads one or more items of any type from the stream associated with the
FILE
object addressed by
f
. The
size
function defines the
size of each item,
count
defines the number
of items to be read, and
ptr
addresses
the area into which the items are to be read.
Although
fread
may
be used to read characters, it is more frequently used to read noncharacter
data, such as structured data. Except when
fread
is used to read printable character data, you should limit its use
to binary streams because the library's transformation of control characters
may change the data in unpredictable ways when reading and writing text streams.
Calls to
fread
to
obtain items of type
typeval
commonly have
this form:
typeval buf[count]; fread(buf, sizeof(typeval), count, f);
RETURN VALUE |
fread
returns the number of items successfully read. It returns 0 if no items are
read because of an error or an immediate end of file.
CAUTION |
When using
fread
, remember that
size
is not
necessarily a multiple of the record size, and that
fread
ignores record boundaries.
DIAGNOSTICS |
The return value from
fread
does not indicate whether the call is completely successful.
You can use the
ferror
function to determine
whether an error occurs.
If
fread
returns
a value of 0, but
count
is greater than
0, an error or end of file occurred before any items were read.
Attempting to read a fraction of an item (for example,
calling
fread
with a size of 4 when the
file contains three characters) is an error.
PORTABILITY |
IMPLEMENTATION |
If
count
is less than one, no input takes place. If an error occurs during the input
operation, the file position is unpredictable.
EXAMPLE |
#include <stdio.h> #include <stdlib.h> main() { FILE *inf, *outf; int data[40]; size_t count; if ( (inf=fopen("tso:READ", "r")) == NULL ) { fprintf(stderr, "Can't open READ.\n"); exit(1); } if ( (outf=fopen("tso:WRITE", "w")) == NULL ) { fprintf(stderr, "Can't open WRITE.\n"); exit(1); } while ( !ferror(inf) && !ferror(outf) ) { /* Test for error. Read items from READ and store */ /* the number of items read in count. */ count = fread(data, sizeof(data[0]), 40, inf); if (count == 0) break; /* Write items to WRITE and store the number of */ /* items written into count. */ count = fwrite((void*)data, sizeof(data[0]), count, outf); if (count < 40) break; } fclose(inf); fclose(outf); }
RELATED FUNCTIONS |
SEE ALSO |
Chapter Contents |
Previous |
Next |
Top of Page |
Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.