您的位置:首页 > 移动开发

ofstream ofile("a.txt", ios_base::app)和ofstream ofile("a.txt", ios::app)有什么区别

2013-07-02 15:15 465 查看


转自: http://zhidao.baidu.com/question/71154325.html

2008-10-09 16:01yifengvic | 分类:网站使用 | 浏览3516次
#include<fstream>
#include<iostream>
using namespace std;
void main()
{
ofstream outfile;
outfile.open("abc.txt",ios::app);
outfile<<"hello\nworld!\n";
outfile.close();
}
和
#include<fstream>
#include<iostream>
using namespace std;
void main()
{
ofstream outfile;
outfile.open("abc.txt",ios_base::app);
outfile<<"hello\nworld!\n";
outfile.close();
}
两者都是正确的,这和命名空间有关吗?
我在书看到讲:要在已存在的文件尾加入新的内容是用
ios::ate
但我用
outfile.open("abc.txt",ios::ate);打开却总是覆盖以前的文件?
ios::ate和ios::app有什么区别?






2008-10-12
20:42提问者采纳

app, to seek to the end of a stream before each insertion.
ate, to seek to the end of a stream when its controlling object is first created.
in, to permit extraction from a stream.
out, to permit insertion to a stream.
就是说,app是文件流被打开后,每次执行outfile<<"hello\nworld!\n";的过程中,文件指针都移动到文件的末尾,就是在末端进行append。
ate是文件流被第一次打开的时候将文件指针移动到文件末尾,然后你可以通过outfile.seekp( pos );将指针移动到pos位置,就是说,在执行outfile<<str;过程中,文件指针你可以自己控制。当然,要是不seek的话会保持在末尾。

至于你说的覆盖以前的文件,是因为你没有指定ios_base::in,而默认为ios_base::out,导致文件被覆盖。具体里面的实现我就不清楚了。呵呵。反正app+out没事,ate+out就不能实现其功能了。我怀疑是不是里面的标志位有逻辑的冲突。你可以细致的研究一下。等你的好消息。

void main()
{
ofstream outfile;
outfile.open("c:\\abc.txt",ios::ate | ios::out );
outfile<<"ddddd";
outfile.seekp( 0 ); //move the file pointer to the beginning.
outfile<<"a";
outfile.close();
}
可以看见a把第一个d覆盖了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐