I'm making a program that copies a file from client to server. I have to send the length of the file to the server before copying. Both of the programs work fine, until I add int sizeFile = getSizeFile(originalFile);
in the client part of my program. All of a sudden (after I add the function) the while()
loop in my server gets stuck on recv()
. And the while()
in my client just loops once and then breaks.
Why does my program work fine until I add the getSizeFile()
function and how can I solve it?
function:
int getSizeFile(FILE* file)
{
// get file size
FILE *f = file;
fseek(f, 0L, SEEK_END);
int sizeFile = ftell(f);
return sizeFile;
}
server:
char ch[70];
printf("where do you want to save it(full path name): ");
scanf_s("%s", ch, 70);
char c[70];
printf("which file you want to copy(full path name): ");
scanf_s("%s", c, 70);
r = send(s, c, 70, 0); // B
if (r == SOCKET_ERROR)
{
printf("2 error: %d\n", WSAGetLastError);
}
FILE* copyFile;
fopen_s(©File, ch, "wb");
if (copyFile == NULL)
{
printf("Error opening file\n");
}
char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;
while (1)
{
int res = recv(s, buf, BUFSIZE, 0);
if (res == SOCKET_ERROR)
{
printf("3 error %d\n", WSAGetLastError);
break;
}
size = fwrite(buf, 1, res, copyFile);
printf("size: %d\n", size);
printf("res: %d\n", res);
counter ;
printf("counter: %d\n", counter);
}
fclose(copyFile);
client:
char c[70];
res = recv(ClientSocket, c, 70, 0); // B
if (res == SOCKET_ERROR)
{
printf("Server disconeccted\n");
break;
}
FILE* originalFile;
fopen_s(&originalFile, c, "rb");
if (originalFile == NULL)
{
printf("Error opening file\n");
}
char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;
int sizeFile = getSizeFile(originalFile); // <-- this one
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;
}
printf("size: %d\n", size);
printf("r: %d\n", r);
counter ;
printf("counter: %d\n", counter);
}
fclose(originalFile);
CodePudding user response:
Would make this a comment since it just riffs off what Alex F said, but not enough reputation. In any case, if you add rewind(f);
after int sizeFile = ftell(f);
in getSizeFile(FILE* file)
, that should solve the issue of not being able to read the file properly.