用ofstream向文件里追加数据失败

Arnis1973 2011-01-20 08:43:42
用ofstream向文件里追加数据失败, 每次都是重写文件. 不是追加.

ofstream stream("save.dat",ios::app | ios::out );
stream << strLine.c_str() << "\n";
...全文
922 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
Arnis1973 2011-01-20
  • 打赏
  • 举报
回复
谢, 的确是这句的问题
我啃 2011-01-20
  • 打赏
  • 举报
回复
_wfopen_s(&fp, _T("save.dat"),_T("wb"));
这句的问题,还有不要混用c和C++的io库设施,会死人的
bluesky12312388 2011-01-20
  • 打赏
  • 举报
回复
不明白你这是干嘛,

_wfopen_s(&fp, _T("save.dat"),_T("wb"));
//这句打开save.dat如果文件存在将内容清空
看看是不是这里的问题

MSDN:
"w"

Opens an empty file for writing. If the given file exists, its contents are destroyed.

bluesky12312388 2011-01-20
  • 打赏
  • 举报
回复
channelData2.close();
这句前面加句
channelData2.flush();


在这
ofstream stream("save.dat",ios_base::app | ios_base::out );
stream << strLine.c_str() << "\n";
后面加上 stream.flush();
stream.close();
在看看结果。
Arnis1973 2011-01-20
  • 打赏
  • 举报
回复
改成这样了还是不行
ofstream stream("save.dat",ios::app | ios::out );
stream << strLine.c_str() << endl;
stream.close();
我啃 2011-01-20
  • 打赏
  • 举报
回复
为什么是ios_base
还有还是close一下比较好
还有'\n'为什么不用endl它会给你自动flush一次
试着手工flush一下
Arnis1973 2011-01-20
  • 打赏
  • 举报
回复
void SaveChannelSelect()
{
int i=0;
size_t pos1,pos2,pos3;
string selectChannel;
MarshalString(CHostWPFWnd::hostedWnd->currentChannel, selectChannel);
string strLine;
ifstream channelData("data.htm");
while(getline(channelData, strLine))
{
string tmpStr;
pos1 = strLine.find("|");
tmpStr = strLine.substr(pos1+1);
pos2 = tmpStr.find("|");
string str = " " + tmpStr.substr(0, pos2);
if(selectChannel == str)
{
FILE * fp = NULL;
_wfopen_s(&fp, _T("save.dat"),_T("wb"));
USES_CONVERSION;
fclose(fp);
bool canSave = true;
string strLine2;
ifstream channelData2("save.dat");
while(getline(channelData2, strLine2))
{
if(strLine == strLine2)
{
canSave = false;
break;
}
}
channelData2.close();
if(canSave)
{
ofstream stream("save.dat",ios_base::app | ios_base::out );
stream << strLine.c_str() << "\n";
}
}
tmpStr = tmpStr.substr(pos2+1);
i++;
}
}

就是这个函数
bluesky12312388 2011-01-20
  • 打赏
  • 举报
回复
[Quote=引用楼主 focuslight 的回复:]
用ofstream向文件里追加数据失败, 每次都是重写文件. 不是追加.

ofstream stream("save.dat",ios::app | ios::out );
stream << strLine.c_str() << "\n";
[/Quote]
按你这代码是追加的。
莫非LZ还做了别的操作。
如果是,请将代码贴全。
zy020118 2011-01-20
  • 打赏
  • 举报
回复
我这按LZ的代码都是追加呢。。
我啃 2011-01-20
  • 打赏
  • 举报
回复
有个开关叫什么append还是什么的

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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