C++实现的FTP案例代码解析

2016-01-05 19:46:22|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:C/C++, 网络通信|来源:唯设编程网

1. 构造函数

CFTP::CFTP(const char* ip, const char* logFile):
m_pLogFile(NULL)
{ 
	//清空
	memset(m_ip,0,sizeof(m_ip));
	//保存IP地址
	strcpy_s(m_ip,ip);

	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD( 2, 2 );
	/*wVersionRequested参数用于指定准备加载的Winsock库的版本。高位字节指定所需要的
	Winsock库的副版本,而低位字节则是主版本。然后,可用宏MAKEWORD( X , Y )(其中,x是
	高位字节, y是低位字节)方便地获得wVersionRequested的正确值。*/	
	if(err = WSAStartup( wVersionRequested, &wsaData ))
	{
		std::cout << "Can not initilize winsock.dll" << std::endl;
		std::cout << "Error Code:" << WSAGetLastError() << std::endl;
		return;
	}else{
		std::cout << "winsock.dll loded" << std::endl;
	}

	/* Confirm that the WinSock DLL supports 2.2.*/
	/* Note that if the DLL supports versions greater    */
	/* than 2.2 in addition to 2.2, it will still return */
	/* 2.2 in wVersion since that is the version we      */
	/* requested.                                        */

	if ( LOBYTE( wsaData.wVersion ) != 2 ||
		HIBYTE( wsaData.wVersion ) != 2 ) {
			/* Tell the user that we could not find a usable */
			/* WinSock DLL.                                  */
			WSACleanup( );
			return; 
	}
	//打开日志文件	
	m_pLogFile = fopen(logFile,"ab+");
} 

构造函数包含两个参数,一个是ip地址,一个是日志文件的路径,在构造函数中主要完成两部分工作,一是对socket环境进行初始化,而是以追加状态打开日志文件。

2. 析构函数

CFTP::~CFTP(void) 
{ 
	WSACleanup();
	//关闭日志文件	
	if(m_pLogFile != NULL){
		fclose(m_pLogFile);
		m_pLogFile = NULL;
	}
} 

析构函数中调用了WSACleanup函数,还有一个功能就是关闭日志文件。

发表评论0条 】
网友评论(共?条评论)..
C++实现的FTP案例代码解析