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

来源:互联网 发布:javascript能干什么 编辑:程序博客网 时间:2024/05/26 19:20

转自: 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覆盖了