Help determining vector / array size - Language C

2

What I would like to do is put in a vector or array, information from a txt file without prior knowledge of the number of "entries" to know the size of the array or array.

With the size of the array or array, I can invoke the function malloc and then read the contents of the file.

Could someone advise me the best way to do it? Thank you.

    
asked by anonymous 17.12.2014 / 23:22

2 answers

1

To know the size of the file, you can go to the end of the file and then get the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

And then, you can go back to the beginning of the file:

fseek(fp, 0L, SEEK_SET);

Source: link

    
17.12.2014 / 23:50
0

If the entries have a defined and unique size, all you have to do is pick up the file size and divide by the size of the entry. The result is the number of entries.

If the size of the entries varies, things get a bit more difficult, but you can try:

  • Use a linked list or a tree or some other type of data structure;

  • Make an estimate that is not less than the number of entries and leave some positions of the array left at the end if you overestimated the number;

  • Scroll through the entire file only to find out the number of entries and then go through it again to populate the array.

17.12.2014 / 23:41