当我没有 endl c++ 时 ofstream 不输出

ofstream not outputting when I don't have a endl c++

我有一个 client/server 套接字程序,它在 char[2048] 中写入文件数据包,我已经 100% 确定在通过套接字发送之前以 null 终止所有数组。

但是在服务器端,如果我没有 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] = '[=10=]';




        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] = '[=11=]';
        fout << EchoBuffer << endl; //If I don't have this endl, it won't work at all




    }

    fout.close();
    close(ClntSocket);    // Close client socket
}

你应该在fout << EchoBuffer;之后写fout.flush();