上传文件函数

BOOL File_Upload(char *path, char *sendbuffer, int bufferlen, SOCKET sock)
{
	HANDLE	fHandle;
	BOOL	Result;
	BOOL	DataSend;
	DWORD	FileSize = 0;
	DWORD	dwBytesRead = 0;
	DWORD	oncelen = 0;
	DWORD	totollen = 0;

	fHandle = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (fHandle == INVALID_HANDLE_VALUE)
	{
		printf("Upload GreateFile Faild.\nError Code is %d\n", GetLastError());
		return FALSE;
	}
	FileSize = GetFileSize(fHandle, NULL);
	sprintf_s(sendbuffer, bufferlen, "%d", FileSize);
	sendbuffer[strlen(sendbuffer)] = 0;
	DataSend = SendPacket(sock, sendbuffer, strlen(sendbuffer) + 1);
	if (DataSend == FALSE)
	{
		printf("Upload FileSize Send Faild.\n");
		return FALSE;
	}
	do
	{
		if (FileSize - totollen > bufferlen)
		{
			oncelen = bufferlen;
		}
		else
		{
			oncelen = FileSize - totollen;
		}
		do
		{
			Result = ReadFile(fHandle, sendbuffer, oncelen, &dwBytesRead, NULL);
			if (Result == 0)
			{
				printf("Upload ReadFile Faild : %u", GetLastError());
				return FALSE;
			}
		} while (dwBytesRead < oncelen);
		DataSend = SendPacket(sock, sendbuffer, dwBytesRead);
		if (DataSend == FALSE)
		{
			printf("FileDownload Send Faild.\n");
			return FALSE;
		}
		totollen += oncelen;
	} while (totollen < FileSize);
	CloseHandle(fHandle);
	return TRUE;
}

注:

1.函数的buffer长度需要通过一个参数传入。

2.使用ReadFile函数时,如果文件句柄未关闭,可以接着上次读到的结尾继续读。