【问题标题】:reading and appending a file using fstream in C++在 C++ 中使用 fstream 读取和附加文件
【发布时间】:2012-10-17 21:09:35
【问题描述】:

我正在尝试使用 fstream 读取文件。然后当我到达最后我附加文件并写一些工作人员 文件

abc

我写了示例代码

#include<iostream>
#include<fstream>
#include<queue>

using namespace std;
int main(int argc, char **argv){
    fstream *binf;
    binf=new fstream("t.txt", ios::out|ios::in|ios::app);
    cout<<"EOF"<<EOF<<endl;
    while(true){
        cout<<"before peek"<<endl;
        cout<<"binf->tellg:"<<binf->tellg()<<endl;
        cout<<"binf->tellp:"<<binf->tellp()<<endl;
        cout<<"binf->peek()::int=("<<(int)binf->peek()<<")::char=("<<(char)binf->peek()<<")"<<endl;
        cout<<"after peek"<<endl;
        cout<<"binf->tellg:"<<binf->tellg()<<endl;
        cout<<"binf->tellp:"<<binf->tellp()<<endl;
        char c;
        if(binf->peek()==EOF){
            cout<<"file is not good"<<endl;
            break;
        }
        binf->get(c);
    }
    cout<<"binf->tellg:"<<binf->tellg()<<endl;
    cout<<"binf->tellp:"<<binf->tellp()<<endl;
    binf->seekg(3);
    binf->seekp(3);
    cout<<"binf->tellg:"<<binf->tellg()<<endl;
    cout<<"binf->tellp:"<<binf->tellp()<<endl;
    binf->put('H');
    cout<<"binf->tellg:"<<binf->tellg()<<endl;
    cout<<"binf->tellp:"<<binf->tellp()<<endl;
    binf->seekg(4);
    char c;
    binf->get(c);
    cout<<"c:"<<c<<endl;
    binf->clear();
    binf->close();
    delete binf;
    return 0;
}

这是我运行此代码得到的输出

EOF-1
before peek
binf->tellg:0
binf->tellp:0
binf->peek()::int=(97)::char=(a)
after peek
binf->tellg:0
binf->tellp:0
before peek
binf->tellg:1
binf->tellp:1
binf->peek()::int=(98)::char=(b)
after peek
binf->tellg:1
binf->tellp:1
before peek
binf->tellg:2
binf->tellp:2
binf->peek()::int=(99)::char=(c)
after peek
binf->tellg:2
binf->tellp:2
before peek
binf->tellg:3
binf->tellp:3
binf->peek()::int=(10)::char=(
)
after peek
binf->tellg:3
binf->tellp:3
before peek
binf->tellg:4
binf->tellp:4
binf->peek()::int=(-1)::char=(ÿ)
after peek
binf->tellg:-1
binf->tellp:-1
file is not good
binf->tellg:-1
binf->tellp:-1
binf->tellg:-1
binf->tellp:-1
binf->tellg:-1
binf->tellp:-1
c:

我要做的就是修复文件并在最后写入 但是,每当我在文件末尾看到 EOF 时,该文件就不再好用了 即使使用 peek()

【问题讨论】:

    标签: c++ file append fstream


    【解决方案1】:

    当您到达文件末尾时,您会将fstream 置于错误状态。当它处于错误状态时,除非您清除错误状态,否则将无法正常工作。所以你需要这个

       if(binf->peek()==EOF){
            cout<<"file is not good"<<endl;
            binf->clear(); // clear the error state
            break;
       }
    

    您无需在关闭 fstream 之前将其清除,这没有任何作用。

    顺便说一句,很好的调试技术,但如果你学会使用合适的调试器,你会发现这更容易。

    【讨论】:

    • 谢谢,你的回答很清楚。我认为 clear 会将缓冲区清除到内存中。
    • 不是flush(),但是当你关闭流时也会自动发生。
    • 是否可以在文件的开头或文件的中间寻回并放置字符
    • 是的,但是您将覆盖已经存在的字符。不能在文件中间插入字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多