Advertisement
Aminpro

[ECP 1016]Tutorial 11 Question 3 [LecturerTANG SZE YIN]

Sep 10th, 2012
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. //https://www.facebook.com/AminproPastebin
  2.  
  3. // Solution for Question 3 Tutorial 11
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. // Part (a) Define a structure called Participant.
  7. struct Participant
  8. {
  9.     int id;
  10. char name[20];
  11.     int time;
  12. };
  13. // Function prototype for find.
  14. void find(struct Participant * list, int size, struct Participant * win);
  15. int main()
  16. {
  17.     // (b) Deduce the total number of participants from the file “results.txt”.
  18. FILE * fptr;      // file pointer
  19.     int count = 0;    // to count total number of participants
  20.     char buff[100];   // temporary buffer for fgets
  21.     fptr = fopen("results.txt", "r");
  22.     if (fptr == NULL)
  23.     {
  24.         printf("Error opening file to read.\n");
  25.         return 1;
  26.     }
  27. while (!feof(fptr))
  28.     {
  29.         fgets(buff, 100, fptr);
  30.         count++;
  31.     }
  32. printf("Total number of participants: %d\n", count);
  33.    
  34. // (c) Declare a pointer of type struct Participant named listptr.
  35. // Use dynamic memory allocation to allocate memory space.
  36. struct Participant * listptr;    // pointer to a list of participant records
  37.     listptr = (struct Participant *) calloc(count, sizeof(struct Participant));
  38.    
  39. // (d) Design a for loop to read information from the file “results.txt”
  40. // to the memory space pointed by listptr.
  41. int i;
  42. rewind(fptr);    // rewind the pointer to the beginning
  43.     for (i=0; i<count; i++)
  44.     {
  45.         fscanf(fptr, "%d %s %d", &listptr[i].id, listptr[i].name, &listptr[i].time);
  46.     }
  47. fclose(fptr);    // close the file
  48.    
  49. // (f) Write the winner information to the end of the file “results.txt”.
  50. struct Participant winner;          // the winner record
  51.     find(listptr, count, &winner);       // call function find
  52.     fptr = fopen("results.txt", "a+");   // append if file exists
  53.     if (fptr == NULL)
  54.     {
  55.         printf("Error opening file to append.\n");
  56.         return 1;
  57.     }
  58. fprintf(fptr, "\n\nThe winner is %s (ID: %d), time taken %ds.",
  59.                   winner.name, winner.id, winner.time);
  60.     fclose(fptr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement