【问题标题】:Add line in .txt update or if line does not exist does not work在 .txt 更新中添加行或如果行不存在则不起作用
【发布时间】:2022-06-14 23:50:35
【问题描述】:

我正在尝试编写一个程序,用其中的单词替换特定行,或者如果文件中不存在该行,则应该添加它。有点像键值存储。

我玩弄了以下代码,不幸的是没有任何结果。要么他只是覆盖了文件并删除了其他行,要么他根本没有写任何东西。最后,这个代码仍然存在。它效率低下且令人困惑,我知道,但也许你可以帮助我。

!!!目前他没有向文件写入任何内容!!!

代码:

            ifstream filein("test.txt");
            ofstream fileout("tempTest.txt);
            if(!filein || !fileout)
            {
                cout << "Error opening files!" << endl;
                return;
            }
            bool found = false;
            string line;
            while(getline(filein, line))
            {
                if(line.find(key) == 0)
                {
                    fileout << key << "=" << value << endl;
                    found = true;
                }
                else
                {
                    fileout << line << endl;
                }
                if(!found)
                {
                    fileout << key << "=" << value << endl;
                }   
            }
            filein.close();
            fileout.close();
            remove("test.txt");
           

【问题讨论】:

  • 是的,我在一个函数里有代码,但是这里没有写

标签: c++ filesystems


猜你喜欢
  • 1970-01-01
  • 2014-07-04
  • 2021-02-09
  • 2018-02-05
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 2011-03-08
相关资源
最近更新 更多