RicardasSim

learning fread feof ferror

Mar 9th, 2019
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define SIZE_OF_BUFFER 10
  5.        
  6. /*        
  7. while(!feof(stream))
  8. {
  9.     ...
  10. }
  11. */
  12.  
  13. int main (int argc, char **argv){
  14.  
  15.     FILE* fp = NULL;
  16.     size_t size;
  17.     char buffer[SIZE_OF_BUFFER];
  18.    
  19.     fp = fopen("example.txt", "rb");
  20.    
  21.     if(fp)
  22.     {
  23.        
  24.         /*
  25.         fread returns the number of objects read
  26.         this may be less than the number requested
  27.         feof and ferror must be used to determine status
  28.         */
  29.        
  30.         size = fread(buffer,1,SIZE_OF_BUFFER,fp);
  31.        
  32.         if(size!=SIZE_OF_BUFFER) printf("info: size differs from SIZE_OF_BUFFER.\n");
  33.            
  34.         if(feof(fp)) printf("info: the EOF flag is set.\n");
  35.         else printf("info: the EOF flag is not set.\n");
  36.            
  37.         if (ferror(fp))
  38.         {
  39.             printf("error: file read error.\n");
  40.             clearerr(fp);
  41.         }
  42.         else printf("info: there is no read error.\n");
  43.  
  44.         fclose(fp);
  45.     }
  46.     else printf("error: can't open file.\n");
  47.    
  48.    
  49. return 0;
  50. }
Add Comment
Please, Sign In to add comment