#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); |
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.
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.
/****************** 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:\nput.txt", "w"); fprintf(fp, "%s", "abcdefghijklmn"); fprintf(fp, "%c", ’\n’); fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn"); fclose(fp); fp = fopen("c:\nput.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"
© 2005-2007 Nokia |