Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://www.facebook.com/AminproPastebin
- // Solution for Question 3 Tutorial 11
- #include <stdio.h>
- #include <stdlib.h>
- // Part (a) Define a structure called Participant.
- struct Participant
- {
- int id;
- char name[20];
- int time;
- };
- // Function prototype for find.
- void find(struct Participant * list, int size, struct Participant * win);
- int main()
- {
- // (b) Deduce the total number of participants from the file “results.txt”.
- FILE * fptr; // file pointer
- int count = 0; // to count total number of participants
- char buff[100]; // temporary buffer for fgets
- fptr = fopen("results.txt", "r");
- if (fptr == NULL)
- {
- printf("Error opening file to read.\n");
- return 1;
- }
- while (!feof(fptr))
- {
- fgets(buff, 100, fptr);
- count++;
- }
- printf("Total number of participants: %d\n", count);
- // (c) Declare a pointer of type struct Participant named listptr.
- // Use dynamic memory allocation to allocate memory space.
- struct Participant * listptr; // pointer to a list of participant records
- listptr = (struct Participant *) calloc(count, sizeof(struct Participant));
- // (d) Design a for loop to read information from the file “results.txt”
- // to the memory space pointed by listptr.
- int i;
- rewind(fptr); // rewind the pointer to the beginning
- for (i=0; i<count; i++)
- {
- fscanf(fptr, "%d %s %d", &listptr[i].id, listptr[i].name, &listptr[i].time);
- }
- fclose(fptr); // close the file
- // (f) Write the winner information to the end of the file “results.txt”.
- struct Participant winner; // the winner record
- find(listptr, count, &winner); // call function find
- fptr = fopen("results.txt", "a+"); // append if file exists
- if (fptr == NULL)
- {
- printf("Error opening file to append.\n");
- return 1;
- }
- fprintf(fptr, "\n\nThe winner is %s (ID: %d), time taken %ds.",
- winner.name, winner.id, winner.time);
- fclose(fptr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement