如何理解这句话?

sxldfang 2011-02-15 09:46:21
如何理解这句话:
ios::trunc If the file already exists, its contents are discarded. This mode is implied if ios::out is specified and ios::ate, ios::app, and ios:in are not specified.

ios::ate The function performs a seek to the end of file. When the first new byte is written to the file, it is appended to the end, but when subsequent bytes are written, they are written to the current position.


ofstream f("d:\\112.txt",ios::ate); // 这样总是把文件截断为0,why?
...全文
150 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaoyu1999 2011-02-15
  • 打赏
  • 举报
回复
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.

VS2010的定义
求指点,如果是第一次创建的话本来指针就是在文件尾的吧
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
已经解决:和ios::in组合使用即可!

#include<iostream>
#include<fstream>
using namespace std;
void main()
{
fstream f("d:\\112.txt",ios::ate|ios::in|ios::out);
f.close();
}
taodm 2011-02-15
  • 打赏
  • 举报
回复
google <标准C++输入输出流与本地化>这本宝典,自己查每种组合的具体含义。
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
9楼的程序在vs2008中同样会截断文件啊!
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
vc++6.0
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
这样说吧,你建一个有内容的文件“d:\112.txt”,再运行下面的程序,文件就被截断为0啦!Why?


#include<iostream>
#include<fstream>
using namespace std;
void main()
{
ofstream f("d:\\112.txt",ios::ate);
f.close();
}
pengzhixi 2011-02-15
  • 打赏
  • 举报
回复
额,不知道你什么编译器,我这vs2008没办法编译你第一个
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 pengzhixi 的回复:]
后面写入多少就覆盖多少
[/Quote]
这个我知道啊,但现在是我写的少,却原来的数据一点也没有啊!


它是在把原文件截断为0长度后才进行的操作啊!
pengzhixi 2011-02-15
  • 打赏
  • 举报
回复
后面写入多少就覆盖多少
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
原文件很长,现在没东西啦,被截断啦!为何一个会截断,一个不会?

若仅是覆盖,不会后面的内容都没了啊!
pengzhixi 2011-02-15
  • 打赏
  • 举报
回复
因为你的f.seekp(0);
所以后面加的内容会覆盖以前的内容
sxldfang 2011-02-15
  • 打赏
  • 举报
回复
为什么用C模式的头文件和用C++模式的头文件效果不一样
比如:下面的代码打开文件时并不会截断原文件的内容#include<iostream.h>
#include<fstream.h>
void main()
{
char c[200];
ofstream f("d:\\112.txt",ios::ate);
f<<"11111111\n";
f.seekp(0);
f<<"222\n";
f.close();
}


但下面的代码会就会截断文件内容,仅头部一样啊
#include<iostream>
#include<fstream>
using namespace std;
void main()
{
char c[200];
ofstream f("d:\\112.txt",ios::ate);
f<<"11111111\n";
f.seekp(0);
f<<"222\n";
f.close();
}
wuyu637 2011-02-15
  • 打赏
  • 举报
回复
王燕的《面向对象的理论与C++实践》:
iso::app 使输出追加到文件尾部
iso::ate 寻找文件尾

ate是否只有第一个byte是追加,如果有后续的byte,就会从头开始覆盖?
wuyu637 2011-02-15
  • 打赏
  • 举报
回复
ios::trunc If the file already exists, its contents are discarded. This mode is implied if ios::out is specified and ios::ate, ios::app, and ios:in are not specified.

trunc模式,如果文件存在,文件的内容会被丢弃,这个模式同时意味着,out输出模式被打开,以及ate,app,in模式是关闭的。



64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧