我正在制作一個將檔案從客戶端復制到服務器的程式。我必須在復制之前將檔案的長度發送到服務器。這兩個程式都可以正常作業,直到我添加int sizeFile = getSizeFile(originalFile);了程式的客戶端部分。突然間(在我添加函式之后) while()我的服務器中的回圈卡在recv(). 而while()我的客戶端中的只是回圈一次然后中斷。
為什么我的程式在我添加getSizeFile()功能之前運行良好,我該如何解決?
功能:
int getSizeFile(FILE* file)
{
// get file size
FILE *f = file;
fseek(f, 0L, SEEK_END);
int sizeFile = ftell(f);
return sizeFile;
}
服務器:
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);
客戶:
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);
uj5u.com熱心網友回復:
會發表評論,因為它只是重復了亞歷克斯 F 所說的話,但沒有足夠的聲譽。無論如何,如果您在inrewind(f);之后添加,那應該可以解決無法正確讀取檔案的問題。int sizeFile = ftell(f);getSizeFile(FILE* file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452963.html
