C ++ - 在不创建新文件的情况下修改文件

时间:2016-02-21 19:42:17

标签: c++

我试图打开一个文件,并修改其中的一些内容。我的第一个代码看起来像这样,

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

using namespace std;

int main(int argc, char** argv) {
    int status = 0;

    //error if no filename
    if(argc == 1) {
        cerr << "No file specified. Please specify a filename" << endl;
        status = 1;
    }

    //open a file and modify
    for (int i = 1; i < argc; ++i) {
        string line = "";
        string filename = argv[i];
        ifstream infile;

        infile.open(filename);
        if(infile.fail()) {
            status = 1;
            cerr << filename << ": No Such File Exist" << endl;
        }
        else{
            while(getline(infile, line)) {
                auto index1 = line.find('(');
                auto index2 = line.find(')');
                cout << index1 << "   " << index2 << endl;
                auto itor = line.begin();
                if(index1 != string::npos)  line[index1] = '[';
                if(index2 != string::npos)  line[index2] = ']';
            }
            infile.close();
        }
    }


    return status;
}

我知道直接修改line是错误的,因为它不会更改文件中的内容。有没有办法可以直接修改文件?(不创建新文件,并输出line

2 个答案:

答案 0 :(得分:2)

你可以:

  1. 将已修改和未修改的行存储在std::vector<std::string>
  2. 关闭文件。
  3. 以写入模式打开文件。
  4. 将存储在std::vector<std::string>中的行保存到文件
  5. 关闭文件。
  6. 最好为每一步创建单独的功能。

    void readContents(std::string const& filename,
                      std::vector<std::string>& lines)
    {
       ...
    }
    
    void updateContents(std::vector<std::string>& lines)
    {
       ...
    }
    
    void WriteContents(std::string const& filename,
                       std::vector<std::string> const& lines)
    {
       ...
    }
    

    然后拨打main

    int main(int argc, char* argv[])
    {
       ...
    
       string filename = argv[i];
       std::vector<std::string> lines;
       readContents(filename, lines);
       updateContents(lines):
       writeContents(filename, lines):
    }
    

答案 1 :(得分:1)

如果您要更改的数据没有以任何方式更改文件的大小(即您没有尝试写入比文件中现有数据更长或更短的数据),那么是的,这是可能的,只要找到它就会覆盖现有数据,方法是改变写入位置。

另一方面,如果数据的大小不同,那么非常很难做到(你需要阅读所有内容并在文件中重新定位),这样更容易写一个新文件并重命名。

将一种支架更改为另一种支架不会改变文件的大小,因此您可以轻松完成。当你找到一个你想要改变的角色时,只需要查看一个角色,set the write pointer到角色的位置并写下新角色。

相关问题