2017-04-23 70 views
0

例子,我有一个sample.txt文件的内容:如何在现有文件中插入文本?

1 2 3 7 8 9 10 

,我想在文件中插入4 5 6

1 2 3 4 5 6 7 8 9 10 

,从而使数字插在正确的地方。

+0

我更新了标题,使其更清晰 – anatolyg

+0

我可以问你将在哪里使用它?我建议将数组中的值存储在json文件中可能是更安全的选择。 – Bram

回答

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 << ' '; 
} 
相关问题