Skip to content
Advertisement

How to find a string in a file and write a new string immediate next line of that search string in a file using C

I need a suggestion to find and write strings in a file using c program.

For example, File.txt has following contents

aaaaa bbbbb
ccccc ddddd
eeeee fffff
ggggg

Here, I want to search a string “ddddd” and write new string (“MMMM NNNN”) after this line like

File will have following contents after addition of new string,

aaaaa bbbbb
ccccc ddddd
MMMM NNNN
eeeee fffff
ggggg

Following is the example Code that I’m trying to make it work and still working on

int main(int argc, char *argv[])
{
    ------
    ------  

    /* Opening a file based on command line argument*/
    fptr = fopen(argv[1], "rw");

    while(fgets(buf, buflen, fptr))
    {
         ------------
        {


            /*Checking the key string "ddddd" and if presents then have to add "MMMM NNNN" in immediate next line*/

            if (strstr(buf, "ddddd"))
            {
                printf("Found Matching for : %sn", argv[3]);
                fprintf(fptr, "n%sn", "MMMM NNNN");
            }
        }
    }
----------
}

Is there any way to update the existing file without creating new file ?

Thanks in advance for your responses.

Advertisement

Answer

You need to “spool” the file. That is, open the file for reading, open a new file for writing, read from the file, “do your stuff” and write to the new file, close the files, delete the old one and rename the new one to the old one. Coding this you must do yourself.

Note that a text file is essentially a sequential file. It means that, would you have opened the file in read/write mode, you cannot “insert” data because that would overwrite other existing data.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement