C/C++为什么ofstream有时候能保存内容有时候不能?
以下为一个接受消息并保存的tcp客户端程序main(){intfds[10];intidx=0;charstr[200];time_ttval;structtm*now;...
以下为一个接受消息并保存的tcp客户端程序
main()
{
int fds[10];
int idx=0;
char str[200];
time_t tval;
struct tm *now;
tval = time(NULL);
now = localtime(&tval);
//Create file
sprintf(str, "./Chat%04d%02d%02d%02d%02d%02d.txt", now->tm_year+1900, now->tm_mon+1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
ofstream ofs1(str);
if(!ofs1)
{
cout << "Create file err: " << str << endl;
return -1;
}
//Create Socket
省略
//Bind
省略
//Listen
省略
//Accept
while(1)
{
fds[idx]=accept(sfd,0,0);
if(fds[idx]==-1) {cout << "accept err!" << endl;return -1;}
cout << "accept user!" << endl;
if(fork())
{
idx++;
cout << "debug:" << idx << endl;
continue;
}
else
{
char buf[256];
while(1) //Recv Msg and print and save to file
{
r=recv(fds[idx],buf,255,0);
if(r<=0) break;
buf[r]='\0';
cout << "::" << buf; //这里可以正常打印
ofs1 << buf ; //这里保存了之后文件却经常没内容
}
close(fds[idx]);
fds[idx]=-1;
cout << "disconnect user!" << endl;
return 0;
}
}
ofs1.close();
close(sfd);
return 0;
} 展开
main()
{
int fds[10];
int idx=0;
char str[200];
time_t tval;
struct tm *now;
tval = time(NULL);
now = localtime(&tval);
//Create file
sprintf(str, "./Chat%04d%02d%02d%02d%02d%02d.txt", now->tm_year+1900, now->tm_mon+1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
ofstream ofs1(str);
if(!ofs1)
{
cout << "Create file err: " << str << endl;
return -1;
}
//Create Socket
省略
//Bind
省略
//Listen
省略
//Accept
while(1)
{
fds[idx]=accept(sfd,0,0);
if(fds[idx]==-1) {cout << "accept err!" << endl;return -1;}
cout << "accept user!" << endl;
if(fork())
{
idx++;
cout << "debug:" << idx << endl;
continue;
}
else
{
char buf[256];
while(1) //Recv Msg and print and save to file
{
r=recv(fds[idx],buf,255,0);
if(r<=0) break;
buf[r]='\0';
cout << "::" << buf; //这里可以正常打印
ofs1 << buf ; //这里保存了之后文件却经常没内容
}
close(fds[idx]);
fds[idx]=-1;
cout << "disconnect user!" << endl;
return 0;
}
}
ofs1.close();
close(sfd);
return 0;
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询