在使用seekg和Tellg之前将数据流式传输到文件时,程序行为异常

时间:2018-10-03 01:57:48

标签: c++ fstream

我将尽可能地保持清楚:每当我尝试在“ do”循环和读取和写入指针之前将数据流式传输到文件中时,我的程序都会发疯!它似乎正在运行无限循环。

fstream fileHandler; //Can also be done via constructor fstream fileHanlder("myData.txt", ios::out);
//fileHandler.open("myData.txt", ios::out);//Default is in AND out

fileHandler.open("test.txt", ios::in | ios::binary | ios::out);

if (fileHandler.is_open()) {

    //fileHandler << "anything" <---HERE IS THE PROBLEM
    cout << "The file has been opened and edited properly.";

    fileHandler.seekg(0, ios::end);
    streampos sizeOfFile = fileHandler.tellg();//tellg returns type streampos
    fileHandler.seekg(0, ios::beg);

    do{
        string buffer;
        fileHandler >> buffer;
        cout << buffer << endl;

    }while(!fileHandler.eof());

    if ((fileHandler.rdstate()^ifstream::eofbit) == 0) {
        fileHandler.clear();
        cout << fileHandler.tellg() << endl;
    }


    fileHandler.close();

} else cout << "There was a problem opening the file!";

我的文件只有一个简单的短语。

编辑:根据新信息修复标题 感谢您的关注!

1 个答案:

答案 0 :(得分:1)

由于某种原因,删除二进制标志已将其修复。谢谢