I have a program which is supposed to (ideally) take an input file, and take dat
ID: 3547679 • Letter: I
Question
I have a program which is supposed to (ideally) take an input file, and take data from the file in order to create new fields of data and output the data in a table. The problem is my program is not reading the input file...and I do not know how to test if its working properly because It can't input the data file. The bold part is the piece of code that inputs the data
code :
#include <stdio.h>
#define NAME_SIZE 25
#define ID_SIZE 9
#define MAX_ASSIGN 6
#define MAX_EXAM 2
#define MAX_STUDENTS 200
#define FILE_SIZE 20
struct student {
char name[NAME_SIZE];
int id[ID_SIZE];
int exam[MAX_EXAM];
int grades[MAX_ASSIGN];
};
typedef struct student studentType;
void printResults(studentType students[], int exams, int assign, int count);
int main()
{
studentType students[MAX_STUDENTS];
int exams, i, e, a, assign;
FILE *data;
char filename[FILE_SIZE];
printf("Enter filename> ");
scanf("%s", &filename);
printf("Enter no of assignments> ");
scanf("%d", &assign);
data = fopen(filename, "r");
printf("Reading from %s ", filename);
if (data == NULL) {
printf("Error reading from %s ", filename);
getchar();getchar();
exit(0);
}
i = 0;
while (fscanf(data, "%s %d", &students[i].name, &students[i].id) >= 2){
for (e=0; e < 2; e++)
fscanf(data, "%d", &students[i].exam[e]);
for (a= 0; a <assign; a++)
fscanf(data, "%d", &students[i].grades[a]);
i++;
}
printResults(students, exams, assign, i);
getchar(); getchar();
return 0;
}
void printResults(studentType students[], int exams, int assign, int count)
{
int i, e, a, sum;
float grade;
for (a = 0; a< assign; a++){
printf(" Name ID Midterm Final ");
for (a=0;a<assign;a++){
printf("Homework %d ", a);
}
printf("Grade ");
printf("------------------------- --------- ------- ----- ");
for (a=0; a<assign; a++){
printf("---------- ");
}
printf("----- ");
}
for (i=0; i < count; i++){
printf("%-20s %d ", students[i].name, students[i].id);
grade = 0;
sum = 0;
for (e=0; e < 2; e++) {
printf("%d", students[i].exam[e]);
}
for (a=0; a< assign; a++){
printf("%d", students[i].grades[a]);
sum += students[i].grades[a];
}
grade = .3*students[i].exam[1]+.3*students[i].exam[2]+.4*sum/assign;
}
printf(" %.2f ", grade);
}
Explanation / Answer
If you are getting an error on fopen check to make sure the data file is in the same directory as your program. You can go deeper by checking the value of the system variable "errno" in your debugger against this list of error codes (http://www.virtsync.com/c-error-codes-include-errno).
Also try sending the full path to your fopen, instead of just the filename.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.