我將在此重新提示整個問題,以便它可以負責。通過TCP/IP連接發送二進制文件
我能夠在不使用套接字的同一臺機器上完美地複製二進制文件,而只是製作一個簡單的複製功能。試圖實現此代碼複製到TCP/IP連接,但無法使其工作。
FILE *filehandle = fopen("imagefile.jpg", "rb");
FILE *dest =fopen("imagecopy.jpg", "wb"); // copied image file
fseek(filehandle, 0, SEEK_END);
unsigned long filesize = ftell(filehandle);
char *buffer = (char*)malloc(sizeof(char)*filesize);
rewind(filehandle);
int bytesread = fread(buffer, sizeof(char), filesize, filehandle);
for(int i=0; i<filesize; i++)
{
fputc(buffer[i], filehandle); // copies all the contents to dest
}
上面的代碼完美地適用於在計算機上覆製圖像文件,但是當實現在服務器上覆制時,很難去處理它。
我試圖從服務器發送圖像文件到客戶都已經手動進行C中的文件的長度由服務器發送時,它的只知道到服務器發送文件,因此緩衝區在服務器中動態生成的,這樣的事情:
服務器
fseek(filehandle, 0, SEEK_END);
long filesize = ftell(filehandle); // file could be 11000bytes
char *buffer = (char*)malloc(sizeof(char)*filesize); // char buffer with 11000 bytes to store the data from the file.
// then I call the send() function
rewind(filehandle); // go back to beginning
send(clientsocket, buffer, filesize, 0); // this is being sent perfectly, no errors because in the actual code, I am checking for errors
CLIENT
// here is where I don't understand how to dynamically allocate the 11000 bytes to store the data in a client buffer
// the filesize is not necessarily going to be 11000 so need to dynamically allocate
// I did the following:
#define BUFSIZE 10
FILE *filehandle = fopen("imagefile.jpg", "wb"); // image file created by client
char *buffer = (char*)malloc(sizeof(char)*BUFSIZE);
int bytesread = recv(buffer, 1, strlen(buffer), 0);
if(bytesread > 0)
{
printf("Bytes read: %d\n", bytesread); // bytes read is 5
printf("Buffer: %s\n", buffer); // but buffer shows all the binary text like it normally would
// when I try to store buffer in a file, it doesn't put full buffer because only 5 characters are written
for(int i=0; i<bytesread; i++)
{
fputc(buffer[i], filehandle); // this doesn't create full image
}
}
如何動態分配服務器發送的11000字節?
你在問爲什麼你沒有顯示的代碼不起作用? – 2014-09-03 00:41:49
未定義的行爲就是 - _undefined_。它不需要崩潰。 – SLaks 2014-09-03 00:42:35
目前還不清楚爲什麼你使用'printf('%s''顯示一個圖像文件 – 2014-09-03 00:42:40