0
例は、私がコンテンツとsample.txt
ファイルがあります:既存のファイルにテキストを挿入するにはどうすればよいですか?
1 2 3 7 8 9 10
を、私は数字が正しい場所に挿入されるように
1 2 3 4 5 6 7 8 9 10
を持っているファイルで4 5 6
を挿入したいです。
例は、私がコンテンツとsample.txt
ファイルがあります:既存のファイルにテキストを挿入するにはどうすればよいですか?
1 2 3 7 8 9 10
を、私は数字が正しい場所に挿入されるように
1 2 3 4 5 6 7 8 9 10
を持っているファイルで4 5 6
を挿入したいです。
ファイルは一般に、テキストを途中で挿入することはできません。ファイルを読み込んで内容を更新し、ファイルを上書きする必要があります。
などのソート済みコンテナを使用します。 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 << ' ';
}
タイトルが明確になるように更新しました – anatolyg
どこでこれを使用するのか尋ねますか?私は、jsonファイルの配列に値を格納することをお勧めします。 – Bram