S
S
Silence2017-06-04 11:34:52
Programming languages
Silence, 2017-06-04 11:34:52

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;
}

I call like this:
load(n,z);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Onito, 2017-06-04
@Onito

Are you limited to only boobs? if not, then here is the solution for you
www.cplusplus.com/reference/cstring/strtok
just split by spaces and use the counter to write to the correct field of the structure

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question