Harikrishnan
Harikrishnan

Reputation: 8065

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. No data is written into the file. neigther the "HI all" nor the received data. 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.

Upvotes: 0

Views: 1882

Answers (1)

dwalter
dwalter

Reputation: 7468

First of all you should check the return value of fopen() to ensure that, log is not NULL. Afterwards, you should use fflush(log) just before 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.

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

Upvotes: 2

Related Questions