我有一个客户端/服务器套接字程序,它在char [2048]中写入文件数据包,我已经100%确定在通过套接字发送之前终止所有数组。
然而,在服务器端,如果我没有endl,我无法将ofstream输出到文件,但是这个endl会在数据包的末尾插入自己并使文件中包含换行符不希望他们这样做。
以下是相关代码
客户端
void Copy(char *filename1,string filename2,int Sockfd) {
const int BUFSIZE=2048;
char buffer[BUFSIZE];
ifstream fin;
long filelen, bytesRemaining, bytes;
// Open the file to be transferred, check it exists.
fin.open( filename1);
if (!fin.good()) {
cerr << "Problems opening \"" << filename1 << "\" (" << errno << "): " << strerror(errno) << endl;
exit(1);
}
// Determine the file's length.
fin.seekg(0,ios::end);
if(fin.fail()) cerr<<"seekg() fail!\n";
filelen = fin.tellg();
if(fin.fail()) cerr<<"tellg() fail!\n";
fin.seekg(0, ios::beg);
if(fin.fail()) cerr<<"seekg() fail!\n";
// Copy the file data.
bytesRemaining = filelen;
while (bytesRemaining > 0)
{
bytes = bytesRemaining > BUFSIZE ? BUFSIZE : bytesRemaining;
buffer[bytes] = '\0';
fin.read(buffer,bytes);
if(fin.fail())
{
cerr<<"read() errror\n";
exit(1);
}
send(Sockfd,buffer,sizeof buffer,0);
recv(Sockfd,buffer,strlen(buffer),0);
bytesRemaining -= bytes;
}
fin.close();
}
和服务器
int retval;
char EchoBuffer[RCVBUFSIZE]; // Buffer for echo string
int RecvMsgSize; // Size of received message
std::ofstream fout;
fout.open("test.txt",std::ios::ate);
// Send received string and receive again until end of transmission
while(RecvMsgSize > 0)
{ // zero indicates end of transmission
// Echo message back to client
if(send(ClntSocket, EchoBuffer, RecvMsgSize, 0) != RecvMsgSize){
perror("send() failed"); exit(1);
}
// See if there is more data to receive
if((RecvMsgSize = recv(ClntSocket, EchoBuffer, RCVBUFSIZE-1, 0)) < 0){
perror("recv() failed"); exit(1);
}
EchoBuffer[RecvMsgSize] = '\0';
fout << EchoBuffer << endl; //If I don't have this endl, it won't work at all
}
fout.close();
close(ClntSocket); // Close client socket
}
答案 0 :(得分:1)
您应该在fout.flush();
之后写下fout << EchoBuffer;
。