Answer the question
In order to leave comments, you need to log in
How to correctly read from a file into a dynamic array?
There is an array of triangle structures, you need to read the length of 3 sides of each triangle from the file. Let's say there is a txt file, it says "1 1 1 2 2 2" roughly speaking, the function should read 2 triangles from the file, 1 with sides 1 1 1 and 2 with sides 2 2 2. I tried it as you like ...
int load (int n, Triangle z[])
{
FILE *f;
char FileName[15];
printf( "Enter the name of file: \n" );
scanf( "%s",FileName );
strcat(FileName,".txt");
if ((f=fopen(FileName, "r")) != NULL)
{
n=0;
z= ( Triangle*)malloc(sizeof( Triangle)); //выделение памяти для одного объекта
fscanf (f,"%lg %lg %lg",&z[0].n,&z[0].m,&z[0].o);
while (!feof(f))
{
n++;
z = realloc(z, (n+1) * sizeof(Triangle));
fscanf (f,"%lg %lg %lg",&z[n].n,&z[n].m,&z[n].o);
}
fclose(f);
printf("Load successful.\n");
}
return n;
}
load(n,z);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question