I am running into problems when I try to transfer a file between the simple server and client applications that I have written. The file gets transferred successfully, but the file size is different at the receiving side (server side). I open the file on the client side, use fseek() to find the size of the file. Then I use fread() to to read it into a buffer of char type. I send this buffer using sendto() as I have to use UDP sockets. On the server side, I use recvfrom() to store this and use fwrite() to write it into another file. But when I check the size of the file, it is much bigger. Also I am not able to open it even though it is supposed to be a text file. Can you give me some pointers as to where I might be going wrong? Also is this the best way to send files over sockets? Are there better methods to send files?
Thanks
Code for client side
//Writing code to open file and copy it into buffer
fseek(fp, 0, SEEK_END);
size_t file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
if(fread(file_buffer, file_size, 1, fp)<=0)
{
printf("Unable to copy file into buffer! \n");
exit(1);
}
//Sending file buffer
if(sendto(sock, file_buffer, strlen(file_buffer), 0, (struct sockaddr *) &serv_addr, serv_len)<0)
{
printf("Error sending the file! \n");
exit(1);
}
bzero(file_buffer, sizeof(file_buffer));
Code on the server side to receive the file
//Receiving file from client
char file_buffer[BUFSIZE];
if(recvfrom(sock, file_buffer, BUFSIZE, 0, (struct sockaddr *) &client_addr, &client_addr_size)<0)
{
printf("Error receiving file.");
exit(1);
}
char new_file_name[] = "copied_";
strcat(new_file_name,file_name);
FILE *fp;
fp = fopen(new_file_name,"w+");
if(fwrite(file_buffer, 1, sizeof(file_buffer), fp)<0)
{
printf("Error writing file! \n");
exit(1);
}