I am writing c programms that sends file thru socket. The client read a binary file and send the content to the server program thru socket. And the client program receive the content of the file and then write it to a file. The programs work well in sending text file but not binary file. I use fopen (xx, "wb"), fread and fwrite. I dun know why it cannot send binary file.
Segments of the code is as follows.
Client.c
ptr = fopen(argv[2],"rb"); /* open the file */
....
while(1)
{
/* read LEN bytes from the file to array data */
read_bytes = fread(data, sizeof(char), LEN, ptr);
/* check reading error */
if (ferror(ptr))
{
perror("error during reading file!");
exit(1);
}
if (read_bytes < LEN)
{
data[read_bytes] = EOF;
read_bytes++;
}
printf("Number of reading byte: %d\n", read_bytes);
printf("%s\n", data);
//send content
//if ((numbytes = sendto(sockfd, data, LEN, 0,
if ((numbytes = sendto(sockfd, data, read_bytes, 0,
(struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) {
perror("sendto");
exit(1);
}
printf("Number of sending byte: %d\n", numbytes);
/* quite the while-loop */
if ( feof(ptr) )
break;
}
........
close(fp)
server.c
/* find the position of EOF */
int findeof(char* content, int size)
{
int i;
for (i=0; i<size; i++)
if (content[i]==EOF)
return i;
/* EOF is not found */
return -1;
}
.....
while(1) // main loop
{
addr_len = sizeof(struct sockaddr);
if ((numbytes=recvfrom(sockfd
, buf, MAXBUFLEN, 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
exit(1);
}
//printf("got packet from %s\n",inet_ntoa(their_addr
.sin_addr)
);
printf("packet is %d bytes long\n",numbytes);
//buf[numbytes] = '\0';
//printf("packet contains \"%s\"\n",buf);
printf("%s\n",buf);
/* write the receive content into the file */
if (findeof(buf, MAXBUFLEN) == -1)
fwrite(buf, sizeof(char), MAXBUFLEN, fp);
else
{
/* no need to write EOF to the file */
fwrite(buf, sizeof(char), findeof(buf, MAXBUFLEN), fp);
printf("location eof %d\n", findeof(buf, MAXBUFLEN));
}
/* quit the loop */
if (findeof(buf, MAXBUFLEN) != -1)
break;
} //END OF WHILE LOOP
...
fclose(fp);
close(sockfd);
Could anyone can help me?
Start Free Trial