Reading txt file in C and data interpretation

Asked

Viewed 348 times

0

I need to read txt files in C and interpret the data from inside the files. The files contain parts in TEXT and others in DECIMAL/INTEGER numbers. What I need to do is 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 the 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 that 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 don’t have enough knowledge 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 part of the file, but as each file will have a different number of lines, how to do this reading without a predefined size?

1 answer

2

I believe the main problem here is dynamic allocation. Obviously the only way to know how much space is needed is to go through the archive to the end. As it is ugly and counterproductive to go through the entire file and then go through it once more, what you have to do is allocate the memory as it is required.

Thinking of pseudocode, it would be something like this:

  1. Starts by allocating 100 items;
  2. If you ask for more, allocate another 100;
  3. And so on and so forth...
  4. Release the remaining unused at the end, if applicable

The perfect function for this job is realloc void* realloc (void* ptr, size_t size);. It is used to increase or decrease the total allocated memory, more or less.

You need to take a lot of care when using it:

  1. Its parameters are the pointer you want to relocate, and the total size you want to relocate;
  2. She 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);
  3. The values previously written on the allocated vector are maintained as they were, although the absolute position in memory changes.

These are the ideas for now. If so, I try a real code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.