简体   繁体   English

fwrite和fprintf在c中不起作用

[英]fwrite and fprintf not working in c

I have written a program to receive a piece of data from a network via socket and write it down to a file. 我编写了一个程序,通过套接字从网络接收数据,然后将其写入文件。 I have used the following code for the purpose: 我已将以下代码用于此目的:

FILE *log;
log = fopen("time.log", "a"); 
fprintf(log,"HI all");
while(1)
{  
    sin_size = sizeof(struct sockaddr_in);
    connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);
    printf("\n I got a connection from (%s , %d)", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    fflush(stdout);           
    while(1)
    {       
        fflush(stdout);
        fgets(send_data,1000,stdin);
        send(connected, send_data,strlen(send_data), 0);
        bytes_recieved = recv(connected,recv_data,1024,0);
        recv_data[bytes_recieved] = '\0';
        char newln[2]="\n";
        int len=strlen(recv_data), len1=strlen(newln);
        fwrite(recv_data, len, 1, log);
        fwrite(newln, len1, 1, log);
        fflush(stdout);
    }
}   
fclose(log);

If the file doesnot exist, the fopen succesfully creates the file, but after that nothing happens. 如果文件不存在,则fopen会成功创建文件,但之后没有任何反应。 No data is written into the file. 没有数据写入文件。 neigther the "HI all" nor the received data. neigther“HI all”也不是收到的数据。 yes, the data is being received, i checked it by printing the received data. 是的,正在接收数据,我通过打印接收的数据来检查它。 Please help me out. 请帮帮我。 Thanks in advance. 提前致谢。 Operating platform is linux. 操作平台是linux。

First of all you should check the return value of fopen() to ensure that, log is not NULL . 首先,你应该检查fopen()的返回值,以确保, log不是NULL Afterwards, you should use fflush(log) just before fflush(stdout) . 之后,你应该在fflush(stdout)之前使用fflush(log) fflush(stdout)

Another thing to mention is that you will never get out of the second while(1) loop, so you should also fix this. 另外要提到的是,你永远不会退出第二个while(1)循环,所以你也应该解决这个问题。

if (bytes_received == 0) {
    /* client closed the connection */
    close(connected);
    break;
}
recv_data[bytes_recieved] = '\0';
char newln[2]="\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM