Reading txt file in C and interpreting the data

0

I need to read txt files in C and interpret the data from within the files. The files contain parts in TEXT and others in DECIMAL / WHOLE numbers. What I need is to read the whole file and pass the numbers to a Cartesian coordinate structure. For example, the contents of the file are:

NAME : eil8
COMMENT : 8-city problem (Christofides/Eilon)
TYPE : TSP
DIMENSION : 8
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 37 52
2 49 49
3 52 64
4 20 26
5 40 30
6 21 47
7 17 63
8 31 62
EOF

I need to read and allocate data from

1 37 52
2 49 49
3 52 64
4 20 26
5 40 30
6 21 47
7 17 63
8 31 62
EOF

in a structure so it looks more or less like this:

coordenada.x[1] = 37;
coordenada.y[1] = 52;

coordenada.x[2] = 49;
coordenada.y[2] = 49;

...

But I do not know enough about dynamic allocation. What I thought:

1- abrir o arquivo
2- ler o arquivo linha por linha até encontrar "NODE_COORD_SECTION"
3- ler o arquivo linha por linha 
4- alocar dinamicamente os dados em uma estrutura tipo matriz x * y
5- parar em EOF

I have knowledge of the code up to the reading portion of the file, but since each file will have a different number of lines, how do I read it without a pre-set size?

    
asked by anonymous 27.04.2017 / 07:32

1 answer

2

I think the main problem here is dynamic allocation. Obviously the only way to know how much space is needed is by traversing the file to the end. Since it is ugly and counterproductive to go through the entire file and then go through it all over again, what you have to do is allocate memory as it is required.

Thinking about pseudocode would look like this:

  • Starts allocating 100 items;
  • If you order more, allocate another 100;
  • And so on ...
  • Release the unused remainder at the end, if applicable
  • The perfect function for this job is realloc void * realloc (void * ptr, size_t size) a>. It is used to increase or decrease the total allocated memory, for more or less.

    You need to be careful when using it:

  • Your parameters are the pointer you want to reallocate, and the total size you want to reallocate;
  • It returns or NULL , in which case it was not possible to allocate the desired memory, or returns a pointer to the new allocated area (which is not necessarily identical to the original);
  • Values previously written to the allocated vector are maintained as they were, even though the absolute position in memory changes.
  • These are the ideas for now. If that's the case, I'll try a real code.

        
    09.05.2017 / 21:38