I am trying to read values from my text file and store them in struct array. My text file has these values:
names.txt
Num_of_rec: 5
3 7 10 1 red
5 6 8 2 red
9 9 16 5 blue
13 4 19 2 green
12 8 15 4 blue
And my code so far is this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ERROR -1
#define MAXLEN 256
struct Point {
float x;
float y;
};
struct Rectangle {
struct Point top_left;
struct Point bottom_right;
char color[7];
};
int main() {
int i, N;
char junk[MAXLEN];
struct Rectangle *data;
FILE *fp;
fp = fopen("names.txt", "r");
fscanf(fp,"%s %d\n",junk,&N);
printf("No: %d", N);
data = (struct Rectangle *) malloc(N*sizeof(struct Rectangle));
for(i=0; i<N; i++) {
fscanf(fp, "%lf %lf %lf %lf %s", data[i].top_left.x, data[i].top_left.y, data[i].bottom_right.x, data[i].bottom_right.y);
}
return 0;
}
I want to add all these values in a struct array(data), but I don't know how to do this properly. Until now the output is:
No: 5
and it just crash. I don't understand if the problem is the method that I am using to read the values from the file and store them to the struct array, or something else.
floattype the format specifiers should be%fnot%lfso you are probably breaking something, because you only provide 4-byte locations not the 8-byte locations expected.data[i].colorin the arguments tofscanf().&before all the other arguments tofscanf(), e.g.&data[i].top_left.x.fp != NULLbefore using the file pointer and you should also validate everyfscanfreturn before considering the data valid.