EDIT: Im trying to send a file from the server to the client. When I send a file of 44 bytes, the client reads in 256 bytes on the first iteration (which is the size of char array buf) and on the next iteration reads the remaining 44 bytes. Why does it not read the 44 bytes initially?
Client snippet ( receives file ):
while((bytes_read = read(sd, buf, sizeof(buf))) > 0){ //receving file contents and writing to file
printf("DEBUG B: read=%zd\n", bytes_read);
fwrite(buf, 1, bytes_read, fp);
total_bytes_read += bytes_read;
printf("DEBUG C: total=%zu\n", total_bytes_read);
if(ferror(fp)){
perror("Error when writing to file\n");
exit(1);
fclose(fp);
}
//printf("Filesize is: %zu \n", filesize);
if(total_bytes_read == filesize){
break;
}
}
printf("The client has received the file\n");
}
server part(sends file):
strcpy(buf, "no issues");
if((y = write(sd, buf, sizeof(buf))) < 0){
perror("Error reporting back to client\n");
}
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("Sending file size\n");
if((write(sd, &filesize, sizeof(filesize))) < 0){ //sending filesize
printf("error sending file size\n");
}
printf("Filesize is: %zu \n", filesize);
printf("Sending file\n");
while((bytes_read = fread(buf, 1, sizeof(buf), fp)) > 0){ //sending file contents
printf("DEBUG A: Bytes read %zu \n", bytes_read);
if ((bytes_written = write(sd, buf, bytes_read)) < 0){
printf("Error sending server file.\n");
}
printf("DEBUG B: Bytes sent %zu \n", bytes_written);
total_bytes_sent += bytes_written;
printf("Total bytes sent %zi \n", total_bytes_sent);
}
printf("File has been sent\n");
fclose(fp);
}
If more code is required I will post it, let me know. Greatly appreciate any help!