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.
First of all you should check the return value of
fopen()to ensure that,logis notNULL. Afterwards, you should usefflush(log)just beforefflush(stdout).Another thing to mention is that you will never get out of the second
while(1)loop, so you should also fix this.