读书人

初学者有关问题:write为什么没有写出

发布时间: 2012-02-10 21:27:42 作者: rapoo

菜鸟问题:write为什么没有写出文件?
用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


[解决办法]
建议用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);
[解决办法]

探讨
建议用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);

[解决办法]
文件还没刷新
在write后加flush试试
[解决办法]
__int64 cin cout 支持的不好
scanf printf 使用 "%I64d" 识别
如果你编译过了 write 不会有问题

读书人网 >C++

热点推荐