使用C 中的Fstream读取和附加文件
reading and appending a file using fstream in C++
我正在尝试使用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()
击中文件末尾时,将 fstream
放入错误状态中。当它处于错误状态时,除非您清除错误状态,否则什么都不会工作。所以你需要这个
if(binf->peek()==EOF){
cout<<"file is not good"<<endl;
binf->clear(); // clear the error state
break;
}
您不需要在关闭它之前清除fstream
。
btw好的调试技术,但是如果您学会使用适当的调试器,您会发现这更容易。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量