How to append text inside an existing file without overwrite?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gilgil
    New Member
    • Jan 2011
    • 1

    How to append text inside an existing file without overwrite?

    Hi, I'm trying to add some strings inside a file in specific locations.
    I'm opening a file with fopen and "r+a"

    and after a while i'm trying to add strings that way:
    Code:
    char *line = (char *) malloc(MAX_LINE);
    while (fgets(line, sizeof(line), theFile) != NULL)
        if (strstr(line, "I want to append here") != NULL)
        	fputs("My new string", theFile);
    But "My new string" will overwrite the next chars from the file.

    example:
    origin file:
    a
    b
    c
    I want to append here
    d
    e
    fffffffffffffff fffffffffffff

    overwrited file
    a
    b
    c
    I want to append here
    My new string
    fffffffffffffff fff


    How can I deal with this problem?
    Thanks in advanced,
    Gil
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    as far as I am aware there is no simple way of inserting records into the middle of a file without overwritting existing records, e.g. see example using fseek()

    you could
    (1) copy the file to another inserting the new record at the required place.
    (2) read the file into an array - do all your insertions (shuffling the array to make room) - then when finished write it out
    (3) if you are dealing with whole lines read the file into a linked list (each element is a line of text) - do the insertions into the list - when finished write the list out to a file

    Comment

    Working...