Name

fread, fwrite
- binary stream input/output

Library

libc.lib

Synopsis

  #include <stdio.h>
  size_t fread (void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);
  size_t fwrite (const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);

Return values

The functions fread and fwrite advance the file position indicator for the stream by the number of bytes read or written. They return the number of objects read or written. If an error occurs, or the end-of-file is reached, the return value is a short object count (or zero).

The function fread does not distinguish between end-of-file and error, and callers must use feof and ferror to determine which occurred. The function fwrite returns a value less than nmemb only if a write error has occurred.


Detailed description

The function fread reads nmemb objects, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

The function fwrite writes nmemb objects, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.


Examples

/****************** this program shows reading characters from a file using fread **************/
/****************** consider input.txt has the following content: ******************************/
/****************** hi ****************************************************************/
#include <stdio.h>
int main()
{
        char a; 
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", ’\n’);
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        fp = fopen("c:\\input.txt", "r");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        // read single chars at a time, stopping on EOF or error:
        while (fread(&a, sizeof(char), 1, fp), !feof(fp) && !ferror(fp))
                {
                printf("I read \"%c\"\n",a);
                }
        if (ferror(fp)) //Some error occurred
                {
                fclose(fp);
                return -1;
                }
        fclose(fp);
        return 0;
}

         

Output

I read "h"
I read "i"

         

See also

read, write

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia

Top