【问题标题】:ofstream not outputting when I don't have a endl c++当我没有 endl c++ 时 ofstream 不输出
【发布时间】:2015-08-21 07:40:53
【问题描述】:

我有一个客户端/服务器套接字程序,它在 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
}

【问题讨论】:

  • 那么你的问题是什么?
  • 你在fout &lt;&lt; EchoBuffer;之后尝试过fout.flush()吗?
  • 我刚试过,确实是这个问题,之前我google的时候提到endl刷新了,但没想太多,非常感谢

标签: c++ sockets client server


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2018-05-23
    • 2014-03-16
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多