reading structure data I\'m done writing a code but can\'t figured out the solut
ID: 3564667 • Letter: R
Question
reading structure data
I'm done writing a code but can't figured out the solution for error. I think it's quite simple fix.
I have 3 files
grades.txt // contains 8 grades
grades.h // structure
grades.c // main
Here are the description of the program is asking
1. Accepting two arguments, 1 for filename grades.txt, and 1 for user ID (ex.123)
2. Display the grades and those average, until I have all 8 grades or met the negative grades
3. Convert user ID into a number uid
4. Read the structure starting at offset (uid*sizeof(struct GR))
**grades.h**
#ifndef GRADE
#define GRADE
struct GR {
float gr[8];
};
#endif
**grades.c**
#include
#include
#include "grades.h"
int main(int argc, char *argv[]) {
struct GR *grades = malloc(sizeof(struct GR));
FILE *file = fopen(argv[1], "rb");
// convert character uid into integer uid
char *chUid = argv[2];
int uid = 0;
int len = strlen(chUid);
for (int i = 0; i < len; i++) {
uid = uid * 10 + (chUid[i] - '0');
}
printf("Converted uid: %d ", uid);
fread(grades, uid * sizeof(struct GR), 1, file);
float total = 0, avg = 0;
int i = 0;
while (i < 9 && grades->gr[i] > 0) {
printf("%d ", grades->gr[i]);
total += grades->gr[i];
i++;
}
printf("Average: %d ", total / i);
return 0;
}
I'm stuck on fread method.. struct is not having any value
Explanation / Answer
Why are u redefining 'i' variable before while loop. Just write "i=0;" instead of "int i=0;"
Also after main, write like this:
struct GR *grades;
grades = (struct GR *) malloc(sizeof(struct GR));
See if this works
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.