Code:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
/*********************************/
/* structure EastDevon*/
struct EastDevon {
char party[2];
char lastName[31];
char firstName[31];
unsigned int votes[4];
struct EastDevon *nextresult;
};
typedef struct EastDevon RESULT;
/* function prototypes */
RESULT ProcessFile (FILE *);
void AddResult (RESULT *, char*, char *, char *, unsigned int, unsigned int, unsigned int, unsigned int);
void PrintList (RESULT *);
/* main function */
int main() {
FILE *fin;
RESULT root;
if ((fin = fopen("EastDevon.txt", "r")) == NULL)
{
printf ("Unable to read file\n");
return EXIT_FAILURE;
}
root = ProcessFile(fin);
PrintList(&root);
fclose(fin);
return EXIT_SUCCESS;
}
/*Reads the file pointed to by fin and constructs a linked list structure,
/* with root as the root result of the tree; */
RESULT ProcessFile (FILE *fin){
RESULT root;
char cParty[2];
char cLastName[31];
char cFirstName[31];
unsigned int C1Votes;
unsigned int C2Votes;
unsigned int C3Votes;
unsigned int C4Votes;
int count = 0;
while (fscanf (fin, "%s%s%s%d%d%d%d", cParty, cLastName, cFirstName, &C1Votes, &C2Votes, &C3Votes, &C4Votes) == 4)
{
count++;
if (count == 1)
{
strcpy(root.party, cParty);
strcpy(root.lastName, cLastName);
strcpy(root.firstName, cFirstName);
root.votes[0]= C1Votes;
root.votes[1]=C2Votes;
root.votes[2]=C3Votes;
root.votes[3]=C4Votes;
root.nextresult = NULL; }
else
AddResult (&root, cParty, cLastName, cFirstName, C1Votes,C2Votes,C3Votes,C4Votes);
}
return root;
}
/*Add a new result to the linked list whose root result is in the first
/*parameter passed to the function */
void AddResult (RESULT *root,
char *cParty,
char *cLastName,
char *cFirstName,
unsigned int C1Votes,
unsigned int C2Votes,
unsigned int C3Votes,
unsigned int C4Votes)
{
RESULT *result = root;
RESULT *newresult = (RESULT *)malloc(sizeof(RESULT));
if (newresult == NULL)
{
printf("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
strcpy(newresult->party, cParty);
strcpy(newresult->lastName, cLastName);
strcpy(newresult->firstName, cFirstName);
newresult->votes[0] = C1Votes;
newresult->votes[1]=C2Votes;
newresult->votes[2]=C3Votes;
newresult->votes[3]=C4Votes;
newresult->nextresult = NULL;
while (result->nextresult !=NULL)
result = result->nextresult;
result->nextresult = newresult;
}
/* print all the results in the linked list */
void PrintList (RESULT *result)
{
if (result == NULL)
return;
printf("%s:%s:%s:%08d\n", result->party, result->lastName,
result->firstName, result->votes[0], result->votes[1], result->votes[2], result->votes[3]);
PrintList(result->nextresult);
}
Now the program should Prompt the user to select which order they wish to see the results in. (i.e last name)