1

这是一个简单的程序,它在文件末尾写入一个换行符,其中包含每行开始的相对位置。

代码:

#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)

似乎getlineinwhile condition首先读abcdline然后将一系列空字符串读入line.

请帮忙。

[编辑]

环境:Win7、Eclipse for C++、Mingw(g++ version 4.7.2)

4

0 回答 0