I have a piece of code to send and receive files on Windows with C. Is this the right way to do it? And am I guaranteed that the full file will be sent and received?
Receiving function:
int recvFile(char path[100], SOCKET y)
{
char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;
int totalRead = 0;
// receiving file size
char b[sizeof(size_t)];
size_t intTotalReceived = 0;
size_t intReceived = 0;
int intSize = sizeof(size_t);
while (intTotalReceived < intSize)
{
intReceived = recv(y, b + intTotalReceived, intSize - intTotalReceived, 0);
if (intReceived == SOCKET_ERROR)
{
printf("error recv buffer size\n");
}
intTotalReceived += intReceived;
}
size_t test = ntohl_ch(&b[0]);
if ((int)test == 666666)
{
return 1;
}
FILE* copyFile;
fopen_s(©File, path, "wb");
if (copyFile == NULL)
{
printf("Error opening file\n");
return 0;
}
while (totalRead < (int)test)
{
int res = recv(y, buf, BUFSIZE, 0);
if (res == SOCKET_ERROR)
{
printf("3 error %d\n", WSAGetLastError());
return 0;
}
size = fwrite(buf, 1, res, copyFile);
counter++;
totalRead += res;
}
fclose(copyFile);
return 1;
}
Sending function:
int sendFile(char path[100])
{
FILE* originalFile;
errno_t fr = fopen_s(&originalFile, path, "rb");
if (fr != 0)
{
printf("Error opening file\n");
int n = 666666;
size_t numb = htonl(n);
char* converted_num = (char*)&numb;
size_t intSize = sizeof(size_t);
size_t intSent = 0;
size_t intTotalSent = 0;
while (intTotalSent < intSize)
{
intSent = send(ClientSocket, converted_num + intTotalSent, intSize - intTotalSent, 0);
if (intSent == SOCKET_ERROR)
{
printf("error send %d\n", WSAGetLastError());
break;
}
intTotalSent += intSent;
}
return 0;
}
char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;
// getting file size
int sizeFile = getSizeFile(originalFile);
// sending file size
size_t num = htonl(sizeFile);
char* converted_num = (char*)#
size_t intSize = sizeof(size_t);
size_t intSent = 0;
size_t intTotalSent = 0;
while (intTotalSent < intSize)
{
intSent = send(ClientSocket, converted_num + intTotalSent, intSize - intTotalSent, 0);
if (intSent == SOCKET_ERROR)
{
printf("error send %d\n", WSAGetLastError());
return 0;
}
intTotalSent += intSent;
}
while (size == BUFSIZE)
{
size = fread(buf, 1, BUFSIZE, originalFile);
int r = send(ClientSocket, buf, size, 0);
if (r == SOCKET_ERROR)
{
printf("1 error: %d\n", WSAGetLastError());
break;
}
counter++;
}
fclose(originalFile);
return 1;
}
And then in main (receiving part):
int r = recvFile(path, y);
if (r == 0)
{
printf("file error\n");
}
Main (sending part):
int ret = sendFile(path);
if (ret == 0)
{
printf("error sending file\n");
}