sockets - receiving a text file in udp in c -


i trying receive text file on udp socket , again save text file. code builds fine when run, output blank console , text file not created well. after research, found out ought give number of bytes received fwrite function tried use size_t type, didn't me :(.

here code snippet:

char file_buffer[100]; while(1) {     // tranmsit data file /     server_length = sizeof(struct sockaddr_in);     if (sendto(sd, send_buffer, (int)strlen(send_buffer) + 1, 0, (struct sockaddr  *)&server, server_length) == -1)     {          fprintf(stderr, "error transmitting data.\n");         closesocket(sd);         wsacleanup();         exit(0);     }     size_t data=0;     if(data=recvfrom(sd, file_buffer, buffer_size, 0, (struct sockaddr *) &server, &server_length)<0)     {         printf("error receiving file.");         exit(1);     }              file *fp=null;     fp = fopen("new_file.txt","w+");     fwrite(file_buffer, 1, data, fp);     {         printf("error writing file! \n");         exit(1);     }     fclose(fp);     printf("file received:)\n");         } 

i appreciate if let me know mistake is.

this mistake due operator precedence:

if(data=recvfrom(sd, file_buffer, buffer_size, 0, (struct sockaddr *) &server, &server_length)<0) 

as < has higher precedence =. means data assigned either 1 or 0 depending on result of < test. change to:

if((data = recvfrom(sd,                     file_buffer,                     buffer_size,                     0,                     (struct sockaddr *) &server,                     &server_length)) < 0) 

ensure file opened before continuing use fp, check result of fwrite() determine status , query errno determine failure reason:

file *fp = fopen("new_file.txt","w+"); if (fp) {     if (fwrite(file_buffer, 1, data, fp) != data)     {         fprintf(stderr, "error writing file: %s\n", strerror(errno));         exit(1);     }     fclose(fp);     printf("file received:)\n"); } else {     fprintf(stderr, "error opening file: %s\n", strerror(errno)); } 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -