2017-04-23 44 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 << ' '; 
} 
相關問題