Advertisement
Guest User

Untitled

a guest
Sep 25th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int readAnimals(const char* filename, ANIMAL* animalPtr, int nrAnimals){
  2. /* pre    :
  3.  * post   : If file contains enough Animals, nrAnimals Animals are read into animalPtr.
  4.  *          If less animals than nrAnimals exist, all animals from the file are read into animalPtr.
  5.  * returns: Nr of animals written into animalPtr or -1 if an error occurs
  6.  */
  7.     int returnValue;
  8.     FILE* f = fopen(filename, "r");
  9.     if ( !f || animalPtr == NULL || nrAnimals <= 0)
  10.     {
  11.         if (!f)
  12.             return -1;
  13.         else
  14.         {
  15.             fclose(f);
  16.             return -1;
  17.         }
  18.     }
  19.     else
  20.     {
  21.         fseek(f, 0, SEEK_END);
  22.         int fileSize = ftell(f);
  23.         int nrAnimalsInFile = fileSize/sizeof(animalPtr);
  24.         fseek(f, 0, 0);
  25.         if (fileSize > 0)
  26.         {
  27.             if (nrAnimalsInFile > nrAnimals)
  28.             {
  29.                 for (int i = 0; i<nrAnimals; i++){
  30.                     fread(&animalPtr[i], sizeof(ANIMAL), 1, f);
  31.                 }
  32.                 returnValue = nrAnimals;
  33.             }
  34.             else
  35.             {
  36.                 for (int i = 0; i<nrAnimalsInFile; i++){
  37.                     fread(&animalPtr[i], sizeof(ANIMAL), 1, f);
  38.                 }
  39.                 returnValue = nrAnimalsInFile;
  40.             }
  41.         }
  42.         else
  43.         {
  44.             fclose(f);
  45.             return -1;
  46.         }
  47.     }
  48.    
  49.    
  50.     fclose(f);
  51.     return returnValue;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement