I want to load a txt file into an array like file() does in php. I want to be able to access different lines like array[N] (which should contain the entire line N from the file), then I would need to remove each array element after using it to the array will decrease size until reaching 0 and the program will finish. I know how to read the file but I have no idea how to fill a string array to be used like I said. I am using gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) to compile.
How can I achieve this?
I suggest you read your file into an array of pointers to strings which would allow you to index and delete the lines as you have specified. There are efficiency tradeoffs to consider with this approach as to whether you count the number of lines ahead of time or allocate/extend the array as you read each line. I would opt for the former.
\nor\r\n)malloc()to allocate a buffer for each and pointed to by the next array indexFor your operations:
array[N]array[N]and setting thearray[N]entry toNULLUPDATE:
The more memory efficient approach suggested by @r.. and @marc-van-kempen is a good optimization over
malloc()ing each line at a time, that is, slurp the file into a single buffer and replace all the line terminators with'\0'Assuming you’ve done that and you have a big buffer as
char *filebufand the number of lines isint num_linesthen you can allocate your indexing array something like this:With a single buffer approach “deleting” a line is merely a case of setting
lines[n]toNULL. There is no free()