Windows TCPファイル転送コード

14506 ワード

WindowsソケットプログラミングTCPファイル転送部
ファイル送信部
// , 
		char file_name[FILE_NAME_MAX_SIZE+1];
		memset(file_name, 0, FILE_NAME_MAX_SIZE+1);
		strncpy(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE:strlen(buffer));
                printf("%s
"
, file_name); FILE * fp = fopen(file_name, "rb"); //windows "rb", if (NULL == fp) { printf("File: %s Not Found
"
, file_name); } else { memset(buffer, 0, BUFFER_SIZE); int length = 0; while ((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0) { if (send(m_New_Socket, buffer, length, 0) < 0) { printf("Send File: %s Failed
"
, file_name); break; } memset(buffer, 0, BUFFER_SIZE); } fclose(fp); printf("File: %s Transfer Successful!
"
, file_name); } closesocket(m_New_Socket); }

ファイルダウンロードセクション
// 
    char file_name[FILE_NAME_MAX_SIZE+1];
	memset(file_name, 0, FILE_NAME_MAX_SIZE+1);
	printf("Please Input File Name On Server: ");
	scanf("%s", &file_name);
 
	char buffer[BUFFER_SIZE];
	memset(buffer, 0, BUFFER_SIZE);
	strncpy(buffer, file_name, strlen(file_name)>BUFFER_SIZE ? BUFFER_SIZE:strlen(file_name));
 
	// 
	if(send(c_Socket, buffer, BUFFER_SIZE, 0) < 0)
	{
		printf("Send File Name Failed
"
); system("pause"); exit(1); } // , FILE * fp = fopen(file_name, "wb"); //windows "wb", if(NULL == fp) { printf("File: %s Can Not Open To Write
"
, file_name); system("pause"); exit(1); } else { memset(buffer, 0, BUFFER_SIZE); int length = 0; while ((length = recv(c_Socket, buffer, BUFFER_SIZE, 0)) > 0) { if (fwrite(buffer, sizeof(char), length, fp) < length) { printf("File: %s Write Failed
"
, file_name); break; } memset(buffer, 0, BUFFER_SIZE); } printf("Receive File: %s From Server Successful!
"
, file_name); } fclose(fp); closesocket(c_Socket);