Continuing from my comments above. Here's what I'd do:
- Create two large,
static char[]
buffers of the same size--each large enough to store the largest file you could possibly ever need to read in (ex: 10 MiB). Ex:
#define MAX_FILE_SIZE_10_MIB (10*1024*1024)
static char buffer_file_in[MAX_FILE_SIZE_10_MIB];
static char buffer_file_out[MAX_FILE_SIZE_10_MIB];
- Use
fopen(filename, "r+")
to open the file as read/update. See: https://cplusplus.com/reference/cstdio/fopen/. Read the chars one-by-one using fgetc()
(see my file_load()
function for how to use fgetc()
) into the first large char buffer you created, buffer_file_in
. Continue until you've read the whole file into that buffer.
- Find the location of the place you'd like to do the insertion. Note: you could do this live as you read the file into
buffer_file_in
the first time by counting newline chars ('\n'
) to see what line you are on. Copy chars from buffer_file_in
to buffer_file_out
up to that point. Now, write your new contents into buffer_file_out
at that point. Then, finish copying the rest of buffer_file_in
into buffer_file_out
after your inserted chars.
- Seek to the beginning of the file with
fseek(file_pointer, 0, SEEK_SET);
- Write the
buffer_file_out
buffer contents into the file with fwrite()
.
- Close the file with
fclose()
.
There are some optimizations you could do here, such as storing the index where you want to begin your insertion, and not copying the chars up to that point into buffer_file_in
, but rather, simply copying the remaining of the file after that into buffer_file_in
, and then seeking to that point later and writing only your new contents plus the rest of the file. This avoids unnecessarily rewriting the very beginning of the fie prior to the insertion point is all.
(Probably preferred) you could also just copy the file and the changes you insert straight into buffer_file_out
in one shot, then write that back to the file starting at the beginning of the file. This would be very similar to @pm100's approach, except using 1 file + 1 buffer rather than 2 files.
Look for other optimizations and reductions of redundancy as applicable.
My approach above uses 1 file and 1 or 2 buffers in RAM, depending on implementation. @pm100's approach uses 2 files and 0 buffers in RAM (very similar to what my 1 file and 1 buffer approach would look like), depending on implementation. Both approaches are valid.