Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ConsoleApplication19.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <stdio.h>
- #include "string.h"
- #include "stdlib.h"
- typedef struct
- {
- char firstName[50];
- char lastName[50];
- long id;
- char english, french, maths, philosophy;
- } result;
- // array of pointers to 'result' structures - assuming that there is 100 or less records in the data file
- result *results[100];
- // number of records read from the file
- int numResults = 0;
- // read file and populate the results
- // you will need to use malloc to allocate a new 'result' structure for each record read from the file
- // the *result pointer returned by malloc will be stored in the next member of the array *results[]
- int readFile(char *fileName);
- // set all the pointers in *results[] to NULL before reading in the file
- void initialiseResults();
- // function to print an individual member of the *results[] array
- void printResult(result *aResult);
- int main()
- {
- char fileName[] = "D:\\results.txt";
- int i = 0;
- void initialiseResults();
- if (!readFile(fileName))
- {
- printf("File could not be opened !!\n");
- return 0;
- }
- printf("%*s\t", 12, "First Name");
- printf("%*s\t", 12, "Second Name");
- printf("ID\tEnglish\tMaths\tFrench\tPhilosophy\n");
- printf("%*s\t", 12, "==========");
- printf("%*s\t", 12, "===========");
- printf("===\t=======\t=====\t======\t==========\n");
- while (results[i] != NULL)
- {
- printResult(results[i]);
- i++;
- }
- return 0;
- }
- void printResult(result *aResult)
- {
- printf("%*s\t", 12, aResult->firstName);
- printf("%*s\t", 12, aResult->lastName);
- printf("%li\t%c\t%c\t%c\t%c\n", aResult->id, aResult->english, aResult->maths, aResult->french, aResult->philosophy);
- }
- void initialiseResults()
- {
- int i = 0;
- while (i < 100)
- {
- results[i] = NULL;
- i++;
- }
- }
- int readFile(char *fileName)
- {
- int i = 0;
- FILE *fptr;
- char buffer[100];
- fptr = fopen(fileName, "r");
- if (fptr == NULL)
- {
- printf("Error opening file\n");
- return 0;
- }
- fgets(buffer, 100, fptr);
- while(!feof(fptr))
- {
- results[i] = (result*)malloc(sizeof(result));
- fscanf(fptr, "%li\t%s\t%s\t%c\t%c\t%c\t%c\n", &results[i]->id, &results[i]->lastName, &results[i]->firstName, &results[i]->english, &results[i]->maths, &results[i]->french, &results[i]->philosophy);
- i++;
- }
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement