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.
- Read the file, counting the number of line terminators you see (ether
\n
or \r\n
)
- Allocate a an array of char * of that size
- Re-read the file, line by line, using
malloc()
to allocate a buffer for each and pointed to by the next array index
For your operations:
- Indexing is just
array[N]
- Deleting is just freeing the buffer indexed by
array[N]
and setting the array[N]
entry to NULL
UPDATE:
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 *filebuf
and the number of lines is int num_lines
then you can allocate your indexing array something like this:
char *lines[] = (char **)malloc(num_lines + 1); // Allocates array of pointers to strings
lines[num_lines] = NULL; // Terminate the array as another way to stop you running off the end
char *p = filebuf; // I'm assuming the first char of the file is the start of the first line
int n;
for (n = 0; n < num_lines; n++) {
lines[i] = p;
while (*p++ != '\0') ; // Seek to the end of this line
if (n < num_lines - 1) {
while (*p++ == '\0') ; // Seek to the start the next line (if there is one)
}
}
With a single buffer approach "deleting" a line is merely a case of setting lines[n]
to NULL
. There is no free()