これは、各行が始まる相対位置を含む改行をファイルの最後に書き込む単純なプログラムです。
コード:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
ofstream fout("copyOut");
fout << "abcd" << '\n' << "efg" << '\n' << "hi" << '\n' << "j" << endl;
fout.close();
cout << "====================== random access to a stream" << endl;
// open for input and output and preposition file pointers to end-of-file
// file mode argument see Chapter 8.4
fstream inOut("copyOut", fstream::ate | fstream::in | fstream::out);
if (!inOut) {
cerr << "Unable to open file!" << endl;
exit(EXIT_FAILURE); // see Section 6.3.2
}
// inOut is opened in ate mode, so it starts out positioned at the end
auto end_mark = inOut.tellg(); // remember original end-of-file position
inOut.seekg(0, fstream::beg); // reposition to the start of the file
size_t cnt = 0; // accumulator for the byte count
string line; // hold each line of input
// while we haven't hit an error and are still reading the orginal data
// and can get another line of input
while (inOut && inOut.tellg() != end_mark && getline(inOut, line)) {
cnt += line.size() + 1; // add 1 to account for the newline
auto mark = inOut.tellg(); // remember the read position
inOut.seekp(0, fstream::end); // set the write marker to the end
inOut << cnt; // write the accumulated length
// print a separator if this is not the last line
if (mark != end_mark)
inOut << " ";
inOut.seekg(mark); // restore the read mark
}
inOut.seekp(0, fstream::end); // seek to the end
inOut << "\n"; // write a newline at end-of-file
inOut.close();
return 0;
}
プログラムを実行した後のファイル「copyOut」の内容は次のとおりです。
abcd
efg
hi
j
5 6 7 8
(there is a blank line at the end of the file)
ただし、予想される内容は次のとおりです。
abcd
efg
hi
j
5 9 12 14
(there is a blank line at the end of the file)
最初に を読み込み、次に空の文字列のシーケンスを に読み込むgetline
ようです。while condition
abcd
line
line
助けてください。
[編集]
環境: Win7、Eclipse for C++、Mingw(g++ バージョン 4.7.2)