【问题标题】:C++ Edit Text File?C++ 编辑文本文件?
【发布时间】:2011-06-07 17:01:08
【问题描述】:

我正在创建一个可以节省大量时间的简单程序,但我有点卡住了。

#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;
}

所以,它现在所做的只是复制一个文件。但我试过这样做,所以它改变了fe。每个“功能”词到“def”,我已经尝试了所有东西并且已经用谷歌搜索了,找不到任何有用的东西,我唯一发现的是使用 sstream,但它毕竟没有用,或者我只是不够熟练,所以如果有人可以给我任何提示或帮助,因为我真的被卡住了吗? :d

【问题讨论】:

  • 说实话,这种简单的文件操作可以更容易地完成,而且使用脚本语言的代码也少得多。诸如 bash 或 Windows PowerShell 之类的 Shell 脚本语言可以在一行代码中真正完成这种事情。
  • 我赞同斯文所说的。你在这里用大锤钉一个图钉。 Python 会是我的推荐,但这只是我 :)
  • 例如,在 bash 中这将是:cat old.lua | sed s/function/def/ &gt; new.lua。在 PowerShell 中,它将是 gc old.lua | foreach { $_ -replace "function", "def" } | sc new.lua

标签: c++ file copy


【解决方案1】:

boost 有一个全部替换功能,它比简单的搜索-替换-重复算法效率更高。这就是我会做的:

std::string file_contents = LoadFileAsString("old.lua");
boost::replace_all(file_contents, "function", "def");
std::ofstream("new.lua") << file_contents;

LoadFileAsString 是我自己的函数,看起来像这样:

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();
}

http://www.boost.org/doc/libs/1_33_1/doc/html/replace_all.html

【讨论】:

    【解决方案2】:

    我真的不明白你的问题。我认为您需要编辑您的帖子并明确询问。

    但您仍然可以对代码进行一项重大改进。您应该以这种方式使用 C++ 流读取文件:

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

    这是使用 C++ 流读取文件的更惯用方式!

    阅读@Jerry Coffin(SO 用户)的这篇优秀博客:

    http://coderscentral.blogspot.com/2011/03/reading-files.html


    编辑:

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

    【讨论】:

    • 嗯,我的问题是,我不知道如何用另一个词替换文件中的每个词。
    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多