#include <stdlib.h>
#include<string.h>
typedef struct monster {
int id;
char name[64];
char element[64];
int population;
double weight;
} monster;
typedef struct {
long long int compares;
long long int copies;
} sort_results;
int main(void) {
monster m[1000],n;
sort_results s;
FILE *file = NULL;
file = fopen("10.txt", "r");
if(file==NULL)
printf("not read");
int i=0;
while(!feof(file)) {
fscanf(file,"%s %s %d %lf", n.name,n.element,&n.population,&n.weight);
n.id = i+1;
/* this commented code gives error segmenatation fault*/
// strcpy(m[i].element,n.element);
// strcpy(m[i].name,n.name);
// m[i].population = n.population;
// m[i].weight = n.weight;
// m[i].id = n.id;
i++;
// this is working fine , printing expected result
printf("%s %s %d %lf\n",n.name,n.element,n.population, n.weight);
}
printf(" \n record count :%d",i);
}
File content
0ybOAtlTP KaRIvi05m 77 1.658986
Zr700nwzB BaFrl3BMN 85 3.019501
SJXVx8seR cMQZZBogi 179 0.237434
n5F30UhgA GPJucKtsW 243 1.082797
BnJBzm9dq NwZKlaEu3 179 5.048067
there is one new line gap in records
1 . this is sample of 5 records , but there can be any number of records present in the file . The statement Fscanf is working fine..it is reading records as expected . But there is more than one record , hence i tried to store them into array , but it throw error as Segmant fault for the commented part of code.
2. Since there is not any fixed amount of records to be read , is their any way to achieve this as every time when it encounters new record in while loop , a new memory block is to be created , some concept of realloc and calloc in C . i tried to achieve this using static allocation of array , but i need this as dynamic