如何在现有文件中插入文本?

时间:2017-04-23 09:16:54

标签: c++ file-io

示例,我有一个内容为sample.txt的文件:

1 2 3 7 8 9 10

我希望在文件中插入4 5 6以便

1 2 3 4 5 6 7 8 9 10

以便将数字插入正确的位置。

1 个答案:

答案 0 :(得分:1)

文件通常不支持在中间插入文本。您应该阅读文件,更新内容并覆盖文件。

使用已排序的容器,例如std::set将文件内容保存在内存中。

std::set<int> contents;

// Read the file
{
    std::ifstream input("file");
    int i;
    while (input >> i)
        contents.insert(i);
}

// Insert stuff
contents.insert(4);
contents.insert(5);
contents.insert(6);

// Write the file
{
    std::ofstream output("file");
    for (int i: contents)
        output << i << ' ';
}