C++ C++;编辑文本文件?

C++ C++;编辑文本文件?,c++,file,copy,C++,File,Copy,我正在创建这个简单的程序,这将节省我很多时间,但我有点卡住了 #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { vector<string> tempfile; string line; ifstream oldfile("old.lua");

我正在创建这个简单的程序,这将节省我很多时间,但我有点卡住了

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> tempfile;
    string line;
    ifstream oldfile("old.lua");
    if (oldfile.is_open())
    {
        while (oldfile.good())
        {
            getline(oldfile, line);
            tempfile.push_back(line + "\n");
        }
        oldfile.close();
    }
    else
    {
        cout << "Error, can't find old.lua, make sure it's in the same directory as this program, and called old.lua" << endl;
    }

    ofstream newfile("new.lua");
    if (newfile.is_open())
    {
        for (int i=0;i<tempfile.size();i++)
        {
            for (int x=0;x<tempfile[i].length();x++)
            {
                newfile << tempfile[i][x];
            }
        }
        newfile.close();
    }
    return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
矢量文件;
弦线;
ifstream oldfile(“old.lua”);
if(oldfile.is_open())
{
while(oldfile.good())
{
getline(旧文件,行);
tempfile.push_back(第+行“\n”);
}
close();
}
其他的
{

我真的不明白你的问题。我认为你需要编辑你的帖子并清楚地问它

<>但是你仍然可以在代码中做一个重大的改进。你应该用C++流读取文件,这样:

while (getline(oldfile, line))
{
    tempfile.push_back(line + "\n");
}

这是用C++流读取文件的更习惯的方式! 阅读@Jerry Coffin(一个SO用户)的这篇优秀博客:


编辑:

您希望查找并替换文件中的文本,然后在本主题中查看接受的答案:


试试这个,

boost有一个replace all函数,它比简单的搜索替换重复算法效率更高。这就是我要做的:

std::string file_contents = LoadFileAsString("old.lua");
boost::replace_all(file_contents, "function", "def");
std::ofstream("new.lua") << file_contents;
std::string file_contents=LoadFileAsString(“old.lua”);
boost::全部替换(文件内容,“函数”、“定义”);

std::of Stream(“new.lua”)老实说,这种简单的文件操作可以更容易地完成,而且使用脚本语言的代码要少得多。bash或Windows PowerShell等Shell脚本语言可以在一行代码中完成这类操作。我支持Sven所说的。你在这里用大锤敲入图钉。Python将是我的建议,但那只是我:)例如,在bash中这将是:
cat old.lua | sed s/function/def/>new.lua
。在PowerShell中它将是
gc old.lua | foreach{$|-replace“function”,“def”}| sc new.lua
。我的问题是,我不知道如何用其他单词替换文件中的每个单词。
std::string LoadFileAsString(const std::string & fn)
{
    std::ifstream fin(fn.c_str());

    if(!fin)
    {
        // throw exception
    }

    std::ostringstream oss;
    oss << fin.rdbuf();

    return oss.str();
}