Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int readAnimals(const char* filename, ANIMAL* animalPtr, int nrAnimals){
- /* pre :
- * post : If file contains enough Animals, nrAnimals Animals are read into animalPtr.
- * If less animals than nrAnimals exist, all animals from the file are read into animalPtr.
- * returns: Nr of animals written into animalPtr or -1 if an error occurs
- */
- int returnValue;
- FILE* f = fopen(filename, "r");
- if ( !f || animalPtr == NULL || nrAnimals <= 0)
- {
- if (!f)
- return -1;
- else
- {
- fclose(f);
- return -1;
- }
- }
- else
- {
- fseek(f, 0, SEEK_END);
- int fileSize = ftell(f);
- int nrAnimalsInFile = fileSize/sizeof(animalPtr);
- fseek(f, 0, 0);
- if (fileSize > 0)
- {
- if (nrAnimalsInFile > nrAnimals)
- {
- for (int i = 0; i<nrAnimals; i++){
- fread(&animalPtr[i], sizeof(ANIMAL), 1, f);
- }
- returnValue = nrAnimals;
- }
- else
- {
- for (int i = 0; i<nrAnimalsInFile; i++){
- fread(&animalPtr[i], sizeof(ANIMAL), 1, f);
- }
- returnValue = nrAnimalsInFile;
- }
- }
- else
- {
- fclose(f);
- return -1;
- }
- }
- fclose(f);
- return returnValue;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement