突然有这个需求,需要在文件中插入一行。找了网上没有找到合适的方案。只好自己写了一个。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>

using namespace std;

bool insert_str_to_file(const char* filename,const char* keyword, const char* insert_content)
{
        FILE* fp          = NULL;
        FILE* fp_tmp      = NULL;
        bool  find_flag   = false;
        char  line[1024]  ={0};

        if ((fp = fopen(filename, "r")) == NULL 
         || (fp_tmp = fopen((string(filename)+"tmp").c_str(), "a")) == NULL )
        {
          cout<<"open file fail"<<endl;
          return false;
        }

		while (fgets(line, sizeof(line) - 1, fp))
		{
			const char* p = NULL;

			if (!find_flag)
			{
				p = strstr(line, keyword);
			}

			fputs(line, fp_tmp);

			if (p && !find_flag)
			{
				find_flag = true;
				fputs(insert_content, fp_tmp);//insert the new content
				fputs("\n", fp_tmp);
			}           
		}

        fclose(fp);
        fclose(fp_tmp);

        string cp_cmd = "cp -f "+ string(filename)+"tmp" + " "+ string(filename);
        system(cp_cmd.c_str());
        string del_cmd = "rm -f "+ string(filename)+"tmp";
        system(del_cmd.c_str());

        return true;
}


int main()
{
    insert_str_to_file("test.txt", "lisi", "wangwu is a boy!");

    return 0;
}

大致算法是:

1.新创建了一个文件。

2. 不断的把源文件的内容读入新文件。

3. 找到关键字时,把要插入的行写入新文件;

4.然后把剩余的内容写入新文件。

5. 最后删除源文件,把新文件变成源文件。

test.txt的内容:

zhangsan is a boy
lisi is a girl
zhaoliu is a boy

执行程序后的内容变为:

zhangsan is a boy
lisi is a girl
wangwu is a boy!
zhaoliu is a boy

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐