I need to write a code that reads a file and then determines a winner but I keep
ID: 3716004 • Letter: I
Question
I need to write a code that reads a file and then determines a winner but I keep getting the error code, that the file is NULL. Can someone help me
//
//
#include <stdio.h>
int main () {
char firstNames[3][20]; // first name
char lastNames[3][20]; // last name
int i; // variable for names
const int numScores = 6; // number of scores, 6
int scores[numScores]; // scores
int j = 0; // variable for scores
int valSum; // sum of the scores
float valAvg[10];
int minScore, maxScore;
float winningScore = 0;
FILE *fp;
fp = fopen("data.txt", "r");
// check if file was successful
if (fp == NULL) {
printf("Program could not open the file. ");
}
else {
// getting the name and storing multiple
for ( i = 0; i < 3; ++i) {
printf(" Please enter the first and last name of the snowboarder, seperated by a space. ");
fscanf(fp, "%s", firstNames[i]);
fscanf(fp, "%s", lastNames[i]);
// read the name back to the user
printf("We will now calculate the average score for ");
printf("%s", firstNames[i]);
printf(" ");
printf("%s", lastNames[i]);
// Entering the scores
printf(" Enter %d scores for the snowboarder. Please seperate by spaces. ", numScores);
for (j = 0; j < numScores; ++j) {
fscanf(fp, "%d", &(scores[j]));
printf("Scores: %d ", scores[j]);
}
// Determine min and max, and then reading it back to make sure program is functioning
minScore = scores[0];
for (j = 0; j < numScores; ++j) {
if (scores[j] < minScore)
minScore = scores[j];
}
maxScore = scores[0];
for (j = 0; j < numScores; ++j) {
if (scores[j] > maxScore)
maxScore = scores[j];
}
printf("Their lowest score was: %d ", minScore);
printf("Their highest score was: %d ", maxScore);
// Determine sum and average
valSum = 0;
for (j = 0; j < numScores; ++j)
{
valSum = valSum + scores[j];
valSum = valSum - (maxScore + minScore);
valAvg[j] = (float) valSum / (float) 4;
printf("Their average score, exluding their highest and lowest is: %f ", valAvg[j]);
}
}
// found out who won !
if (valAvg[j] > winningScore) {
winningScore = valAvg[j];
printf("Drumroll please! .. .. ");
printf("... .... ... ");
printf("The winner is... ");
printf("%s", firstNames[i]);
printf(" with %f points! Congratulations! ", winningScore);
} // end of if, winning score
fclose(fp);
}
} // end of else
// end of main
Explanation / Answer
Your file might not have read permission.
Try
Also, check file location. file location. Make sure your text file is in the same directory as your executable. You'll need to do this if you don't specify file location.