简体   繁体   English

如何在文件中查找字符串并使用 C 在文件中该搜索字符串的下一行立即写入一个新字符串

[英]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.我需要一个使用 c 程序在文件中查找和写入字符串的建议。

For example, File.txt has following contents例如 File.txt 有以下内容

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在这里,我想搜索一个字符串“ddddd”并在此行之后写入新字符串(“MMMM NNNN”),例如

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 : %s\n", argv[3]);
                fprintf(fptr, "\n%s\n", "MMMM NNNN");
            }
        }
    }
----------
}

Is there any way to update the existing file without creating new file ?有没有办法在不创建新文件的情况下更新现有文件?

Thanks in advance for your responses.预先感谢您的回复。

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.这意味着,如果您以读/写模式打开文件,则不能“插入”数据,因为这会覆盖其他现有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM