Home > Enterprise >  How to write at the middle of a file in c
How to write at the middle of a file in c

Time:01-07

Is it possible to write at the middle of a file for example I want to insert some string at the 5th position in the 2nd line of a file in c ? I'm not very familiar with some of C functions that are related to handling files , if someone could help me I would appreciate it

I tried using fputs but I couldn't insert characters at the desired location

CodePudding user response:

Continuing from my comments above. Here's what I'd do:

  1. 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 file_in[MAX_FILE_SIZE_10_MIB];
    static char file_out[MAX_FILE_SIZE_10_MIB];
    
  2. 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, file_in. Continue until you've read the whole file into that buffer.
  3. 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 file_in the first time by counting newline chars ('\n') to see what line you are on. Copy chars from file_in to file_out up to that point. Now, write your new contents into file_out at that point. Then, finish copying the rest of file_in into file_out after your inserted chars.
  4. Seek to the beginning of the file with fseek(file_pointer, 0, SEEK_SET);
  5. Write the file_out buffer contents into the file with fwrite().
  6. 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 file_in, but rather, simply copying the remaining of the file after that into 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.

Look for other optimizations and reductions of redundancy as applicable.

CodePudding user response:

open a new output file

read the input file line by line (fgets) writing each line out to a new file as you read.

When you hit the place you want to insert write the new line(s)

The carry on copy the old lines to the new file

close input and output

rename output file to input

  •  Tags:  
  • c
  • Related