I’m used to PHP, but I’m starting to learn C. I’m trying to create a program that reads a file line by line and stores each line to an array.
So far I have a program that reads the file line by line, and even prints each line as it goes, but now I just need to add each line to an array.
My buddy last night was telling me a bit about it. He said I’d have to use a multidimensional array in C, so basically array[x][y]. The [y] part itself is easy, because I know the maximum amount of bytes that each line will be. However, I don’t know how many lines the file will be.
I figure I can make it loop through the file and just increment an integer each time and use that, but I feel that there might be a more simple way of doing it.
What can I try next?
To dynamically allocate a 2D array:
Modify the above method. When you need another line to be added do
*(p + i) = malloc (sizeof (char) * dim2);and updatei. In this case you need to predict the max numbers of lines in the file which is indicated by thedim1variable, for which we allocate theparray first time. This will only allocate the(sizeof (int *) * dim1)bytes, thus much better option thanchar p[dim1][dim2](in c99).There is another way i think. Allocate arrays in blocks and chain them when there is an overflow.
After this the first block is ready to use. When you need to insert a line just do:
When
nisLINE_MAXallocate another block and link it to this one.Something like this.
When one block’s
nbecomes0, deallocate it, and update the current block pointerfileto the previous one. You can either traverse from beginning single linked list and traverse from the start or use double links.