I'm trying to get this program to open and read a *.txt file and save in an array in traditional C. CLASS is defined as "filename.t xt" in the header file. It reads from the file, I think, but it is nothing but garbage. Please offer suggestions...
I can't wait to understand this language!
Code:
#include "cl_info.h"
void get_class_data(struct student class[])
{
char last_name[MAXWORD];
char line[MAXLINE];
int cnt;
int i = 0;
int n;
FILE *ifp;
ifp = fopen(CLASS, "r");
if (ifp == NULL) {
printf("\nCannot open %s - Goodbye!\n\n", CLASS);
exit(1);
}
for (i = 0; fgets(line, MAXLINE, ifp) != NULL; ++i){
cnt = sscanf_s(line, "%s%d %c",
last_name, &class[i].student_id, &class[i].grade);
assert(cnt == 3);
n = strlen(last_name);
class[i].last_name = calloc(n + 1, sizeof(char));
assert(class[i].last_name != NULL);
strcpy(class[i].last_name, last_name);
}
if (i != CLASS_SIZE) {
printf("\n%s\n\n",
"ERROR: Unexpected class size in %s - Goodbye!\n\n", CLASS);
exit(1);
}
}
Comment