菜鸟问题:write为什么没有写出文件?

albert_skynet 2008-05-12 10:15:53
用write写test.txt和test.bin文件,可是输出是空文件,
代码:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct callerIdx
{
__int64 caller;
long call_no;
};

bool getData (callerIdx& cid);
void writeFile (ofstream& ot, ofstream& ob,callerIdx& cid);


int main()
{

ofstream oftxt;
char* txtName = "test.txt";
oftxt.open (txtName, ios::out | ios::app);
if(!txtName)
{
cout << "\nCannot open " << txtName << endl;
exit (100);
}

ofstream ofbin;
char* binName = "test.bin";
ofbin.open (binName, ios::out | ios::binary | ios::app);
if( !binName )
{
cout << "\nCannot open " << binName << endl;
exit (101);
}
callerIdx Idx;
while (getData (Idx))
{
cout << "Begin Write File!\n";
writeFile (oftxt,ofbin,Idx);
}

oftxt.close();
ofbin.close();

return 0;

} // main
/*===================== getData =======================*/
bool getData (callerIdx& cid)
{
cout << "\nEnter caller : ";
cin >> cid.caller;
cout << "\nEnter IDX Number :";
cin >> cid.call_no;


if(cid.caller > 0 && cid.call_no > 0)
return 1;
else
return 0;
} // getData

/*===================== writeFile =========================*/
void writeFile (ofstream& ot, ofstream& ob,callerIdx& cid)
{
cout << "\nCaller Number is " << cid.caller
<< "\nIdx Number is " << cid.call_no;
ot.write ((char*) &cid,sizeof(callerIdx));
if(!ot.good())
cout << "\nWrite File Error";
ob.write ((char*) &cid,sizeof(callerIdx));
if(!ob.good())
cout << "\nWrite File Error";
cout << " \nFile Write complete!";
return;
} // writeFile
...全文
111 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ly19820701 2008-05-12
  • 打赏
  • 举报
回复
__int64 cin cout 支持的不好
scanf printf 使用 "%I64d" 识别
如果你编译过了 write 不会有问题
hai040 2008-05-12
  • 打赏
  • 举报
回复
文件还没刷新
在write后加flush试试
agaric 2008-05-12
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 yys213 的回复:]
建议用C语言中读写文件函数,原来我也经常用fstream来进行读写文件,这种在C基础上进行封装的,有时会出现莫名奇妙的错误,

FILE *pFile=fopen( "stud.txt ", "a ");
fseek(pFile,0,SEEK_SET);
char*s= "222";
fwrite(s,1,sizeof(s),pFile);
fclose(pFile);
[/Quote]

sizeof(s)是多少? 不出错才怪。
圆圆木公 2008-05-12
  • 打赏
  • 举报
回复
建议用C语言中读写文件函数,原来我也经常用fstream来进行读写文件,这种在C基础上进行封装的,有时会出现莫名奇妙的错误,

FILE *pFile=fopen( "stud.txt ", "a ");
fseek(pFile,0,SEEK_SET);
char*s= "222";
fwrite(s,1,sizeof(s),pFile);
fclose(pFile);

64,646

社区成员

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

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