您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ FormatMessage函数代码示例

51自学网 2021-06-01 20:48:01
  C++
这篇教程C++ FormatMessage函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中FormatMessage函数的典型用法代码示例。如果您正苦于以下问题:C++ FormatMessage函数的具体用法?C++ FormatMessage怎么用?C++ FormatMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了FormatMessage函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: pgsymlink

/* *	pgsymlink - uses Win32 junction points * *	For reference:	http://www.codeproject.com/KB/winsdk/junctionpoints.aspx */intpgsymlink(const char *oldpath, const char *newpath){	HANDLE		dirhandle;	DWORD		len;	char		buffer[MAX_PATH * sizeof(WCHAR) + sizeof(REPARSE_JUNCTION_DATA_BUFFER)];	char		nativeTarget[MAX_PATH];	char	   *p = nativeTarget;	REPARSE_JUNCTION_DATA_BUFFER *reparseBuf = (REPARSE_JUNCTION_DATA_BUFFER *) buffer;	CreateDirectory(newpath, 0);	dirhandle = CreateFile(newpath, GENERIC_READ | GENERIC_WRITE,						   0, 0, OPEN_EXISTING,			   FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0);	if (dirhandle == INVALID_HANDLE_VALUE)		return -1;	/* make sure we have an unparsed native win32 path */	if (memcmp("//??//", oldpath, 4))		sprintf(nativeTarget, "//??//%s", oldpath);	else		strcpy(nativeTarget, oldpath);	while ((p = strchr(p, '/')) != 0)		*p++ = '//';	len = strlen(nativeTarget) * sizeof(WCHAR);	reparseBuf->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;	reparseBuf->ReparseDataLength = len + 12;	reparseBuf->Reserved = 0;	reparseBuf->SubstituteNameOffset = 0;	reparseBuf->SubstituteNameLength = len;	reparseBuf->PrintNameOffset = len + sizeof(WCHAR);	reparseBuf->PrintNameLength = 0;	MultiByteToWideChar(CP_ACP, 0, nativeTarget, -1,						reparseBuf->PathBuffer, MAX_PATH);	/*	 * FSCTL_SET_REPARSE_POINT is coded differently depending on SDK version;	 * we use our own definition	 */	if (!DeviceIoControl(dirhandle,	 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_ANY_ACCESS),						 reparseBuf,	reparseBuf->ReparseDataLength + REPARSE_JUNCTION_DATA_BUFFER_HEADER_SIZE,						 0, 0, &len, 0))	{		LPSTR		msg;		errno = 0;		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,					  NULL, GetLastError(),					  MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),					  (LPSTR) &msg, 0, NULL);#ifndef FRONTEND		ereport(ERROR,				(errcode_for_file_access(),				 errmsg("could not set junction for /"%s/": %s",						nativeTarget, msg)));#else		fprintf(stderr, _("could not set junction for /"%s/": %s/n"),				nativeTarget, msg);#endif		LocalFree(msg);		CloseHandle(dirhandle);		RemoveDirectory(newpath);		return -1;	}	CloseHandle(dirhandle);	return 0;}
开发者ID:50wu,项目名称:gpdb,代码行数:80,


示例2: openRestoreDrives

void image::restoreImage() {	openRestoreDrives();	BYTE* buffer = new BYTE[bufferSize];	LPDWORD bytesRead = new DWORD();			*bytesRead = bufferSize;	dCompress* comp; 	comp= new dCompress();	BYTE* outbuff;	int outbuffersize;//  = 10000;	int returnread = 0;	int returnwrite = 0;	char message[200];	int tValue;	long readSize = 0;	long writeSize = 0;	//DWORD *written = 0;	while (*bytesRead != 0)	{		returnread = ReadFile(hFile[0],buffer,bufferSize,bytesRead,NULL);		//cout << "return read: " << returnread << endl;		//FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),0, message,200,NULL);		//cout << "Message: " << message << endl;		if (buffer [*bytesRead - 1] == (0xFF))		{			if ((buffer [*bytesRead -2] == (0xFE)) && (buffer [*bytesRead-3 ] == 0xFF))			{				SetFilePointer(hFile[0],-3,NULL,FILE_CURRENT);				*bytesRead -= 3;						}				else			{				SetFilePointer(hFile[0],-1,NULL,FILE_CURRENT);				*bytesRead -= 1;			}				}					if	(buffer [*bytesRead - 2] == (0xFF))		{			SetFilePointer(hFile[0],-2,NULL,FILE_CURRENT);			*bytesRead -= 2;		}				comp-> uData(((BYTE*)buffer),*bytesRead, &outbuff, &outbuffersize); 		cout << "ResoreImage, Initial: " << *bytesRead << " Final: " << outbuffersize << " ";		readSize += *bytesRead;		writeSize += outbuffersize;		tValue = outbuffersize - 500;		while (tValue > 0)		{			cout << "*";			tValue -= 100;		}		cout << endl;		 *bytesRead = outbuffersize; //this was here 		//returnwrite = WriteFile(hFile[1],outbuff,outbuffersize,bytesRead,NULL);//this is the correct one	    //returnwrite = WriteFile(hFile[1],buffer,bufferSize,bytesRead,NULL);//origial code		//returnwrite = WriteFile(hFile[1],buffer,outbuffersize,bytesRead,NULL);//fails to read				 //cout << "Buffer size: " << outbuffersize << endl;		cout <<"Read in : "<< *bytesRead<< endl;/*			cout << "File: " << hFile[1] << endl				 << "Buffer: /"" << outbuff << "/"" << endl				 << "oBuffSize: " << outbuffersize << endl;//				 << "bytesWritten: " << *bytesRead << endl;*/		returnwrite = WriteFile(hFile[1],outbuff,outbuffersize,bytesRead,NULL);//this is correct!!		cout <<"Read in after Write: "<< *bytesRead<< endl;		cout << "return write: " << returnwrite << "  bytesRead: " << *bytesRead << endl;		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),0, message,200,NULL);		cout << "Error Message : " << message << endl;		//if (false == returnwrite)		//{//			cout << "File: " << hFile[1] << endl				// << "Buffer: /"" << outbuff << "/"" << endl//				 << "oBuffSize: " << outbuffersize << endl//				 << "bytesWritten: " << *bytesRead << endl;		//}		//dumpbyte(outbuff,10);		//dumpbyte(outbuff+(outbuffersize-10),10);		delete[] outbuff;		//as long as bytesRead==sectorSize the commands		//completed successfully	}		delete bytesRead;	delete [] buffer;	cout << readSize << " bytes read from image file" << endl;//.........这里部分代码省略.........
开发者ID:janemiceli,项目名称:WinImg,代码行数:101,


示例3: fopen

bool CCodeProcessor::TryBuild( const char *rootdir, const char *filename, unsigned char *buffer, int filelength ){//	vprintf( "trying build/n" );	FILE *fp;	fp = fopen( filename, "wb" );	if ( !fp )	{		assert( 0 );		return false;	}	fwrite( buffer, filelength, 1, fp );	fclose( fp );	// if build is successful, return true	//	//	return true;	char commandline[ 512 ];	char directory[ 512 ];	sprintf( directory, rootdir );	//	sprintf( commandline, "msdev engdll.dsw /MAKE /"quiver - Win32 GL Debug/" /OUT log.txt" );	// Builds the default configuration	sprintf( commandline, "/"C://Program Files//Microsoft Visual Studio//Common//MSDev98//Bin//msdev.exe/" %s /MAKE /"%s/" /OUT log.txt", m_szDSP, m_szConfig );	PROCESS_INFORMATION pi;	memset( &pi, 0, sizeof( pi ) );	STARTUPINFO si;	memset( &si, 0, sizeof( si ) );	si.cb = sizeof( si );	if ( !CreateProcess( NULL, commandline, NULL, NULL, TRUE, 0, NULL, directory, &si, &pi ) )	{LPVOID lpMsgBuf;FormatMessage(     FORMAT_MESSAGE_ALLOCATE_BUFFER |     FORMAT_MESSAGE_FROM_SYSTEM |     FORMAT_MESSAGE_IGNORE_INSERTS,    NULL,    GetLastError(),    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language    (LPTSTR) &lpMsgBuf,    0,    NULL );// Process any inserts in lpMsgBuf.// ...// Display the string.MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );// Free the buffer.LocalFree( lpMsgBuf );		return false;	}	// Wait until child process exits.    WaitForSingleObject( pi.hProcess, INFINITE );	bool retval = false;	DWORD exitCode = -1;	if ( GetExitCodeProcess( pi.hProcess, &exitCode ) )	{		if ( !exitCode )		{			retval = true;		}	}	    // Close process and thread handles.     CloseHandle( pi.hProcess );    CloseHandle( pi.hThread );	return retval;}
开发者ID:RaisingTheDerp,项目名称:raisingthebar,代码行数:77,


示例4: UpdateXMLData

bool UpdateXMLData(const Category cat, const char *redirect_url /*= 0*/, int recurse_count /*=0*/) {		if(recurse_count > MAX_REDIRECT_RECURSE) {		PUShowMessageT(TranslateT("Updater: Error getting data - too many redirects"), SM_WARNING);		return false;	}	NETLIBHTTPREQUEST req = {0};	NETLIBHTTPHEADER etag_hdr = {0};	if(OldXMLDataExists(cat)) {		// ensure backend not checked more than once every MIN_XMLDATA_AGE hours		long age = OldXMLDataAge(cat);		if(age >= 0 && age < MIN_XMLDATA_AGE)	{	// get it only if our file is at least 8 hours old#ifdef DEBUG_HTTP_POPUPS			char buff[512];			sprintf(buff, "XML Data is recent (%d hours old) - not downloading, using local copy", age);			PUShowMessage(buff, SM_NOTIFY);#endif			return LoadOldXMLData(cat, false);		}		// add ETag header for conditional get		DBCONTACTGETSETTING cgs;		DBVARIANT dbv;		cgs.szModule = MODULE;		char buff[256];		strcpy(buff, "DataETag_");		strcat(buff, category_files[cat]);		cgs.szSetting = buff;		cgs.pValue = &dbv;		if(!CallService(MS_DB_CONTACT_GETSETTING, 0, (LPARAM)&cgs)) {			req.headersCount = 1;			req.headers = &etag_hdr;			etag_hdr.szName = "If-None-Match";			etag_hdr.szValue = _strdup(dbv.pszVal);			DBFreeVariant(&dbv);		}	}	req.cbSize = sizeof(req);	req.requestType = REQUEST_GET;	char URL[MAX_PATH];	if(!redirect_url) {		strcpy(URL, MIM_BACKEND_URL_PREFIX);		strcat(URL, category_files[cat]);		strcat(URL, ".bz2");	} else {		strcpy(URL, redirect_url);	}	req.szUrl = URL;	req.flags = NLHRF_HTTP11;	req.nlc = hNetlibHttp;	if (CallService(MS_SYSTEM_GETVERSION, 0, 0) >= PLUGIN_MAKE_VERSION(0,9,0,5))		req.flags |= NLHRF_PERSISTENT | NLHRF_REDIRECT;	NETLIBHTTPREQUEST *resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser, (LPARAM)&req);	free(etag_hdr.szValue);	if (!resp) 	{		hNetlibHttp = NULL;		if (!Miranda_Terminated())		{			int err = GetLastError();			if (err) 			{				TCHAR buff[512];				int len = mir_sntprintf(buff, SIZEOF(buff), TranslateT("Failed to download XML data: "));				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, err, 0, buff + len, 512 - len, 0);				ShowError(buff);				//MessageBox(0, buff + len, TranslateT("Updater: Error Downloading XML Data"), MB_OK | MB_ICONWARNING);			} 			else 			{				ShowError(TranslateT("Failed to download XML data - Response is NULL"));				//MessageBox(0, TranslateT("Error downloading XML data.../nResponse is NULL"), TranslateT("Updater Error"), MB_OK | MB_ICONWARNING);				NLog("Failed to download XML data - Response is NULL");			}		}		return LoadOldXMLData(cat, false);	} 	else if (resp->resultCode == 304) { // 'Not Modified' response		hNetlibHttp = resp->nlc;		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);		resp = 0;#ifdef DEBUG_HTTP_POPUPS		PUShowMessage("XML Data unchanged - using local copy", SM_NOTIFY);#endif		// mark data as current		return LoadOldXMLData(cat, true);	} else if(resp->resultCode >= 300 && resp->resultCode < 400) { // redirect response		hNetlibHttp = resp->nlc;		// get new location		bool ret = false;		for(int i = 0; i < resp->headersCount; i++) {			//MessageBox(0, resp->headers[i].szValue, resp->headers[i].szName, MB_OK);//.........这里部分代码省略.........
开发者ID:darkscout,项目名称:sje-miranda-plugins,代码行数:101,


示例5: FormatError

///////////////////////////////////////////////////////////////////////////////++////  FormatError////  Description://      Format an error.////  Arguments://      rstrError   String in which to return the error message.//      dwError     Error code to format.////  Return Value://      None.////--/////////////////////////////////////////////////////////////////////////////voidFormatError(      CString & rstrErrorInout    , DWORD     dwErrorIn    ){    DWORD   cch;    TCHAR   szError[ 512 ];    //    // Format the NT status code from CLUSAPI.  This is necessary    // for the cases where cluster messages haven't been added to    // the system message file yet.    //    cch = FormatMessage(                      FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS                    , ::GetModuleHandle( _T( "CLUSAPI.DLL" ) )                    , dwErrorIn                    , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )                    , szError                    , RTL_NUMBER_OF( szError )                    , 0                    );    if ( cch == 0 )    {        cch = FormatMessage(                          FORMAT_MESSAGE_FROM_SYSTEM                        , NULL                        , dwErrorIn                        , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )                        , szError                        , RTL_NUMBER_OF( szError )                        , 0                        );        if ( cch == 0 )        {            //            // Format the NT status code from NTDLL since this hasn't been            // integrated into the system yet.            //            cch = FormatMessage(                              FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS                            , ::GetModuleHandle( _T( "NTDLL.DLL" ) )                            , dwErrorIn                            , MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)                            , szError                            , RTL_NUMBER_OF( szError )                            , 0                            );        }  // if:  error formatting status code from system    }  // if:  error formatting status code from ClusApi    if ( cch > 0 )    {        rstrErrorInout = szError;    }  // if:  no error    else    {        TRACE( _T( "FormatError() - Error 0x%08.8x formatting string for error code 0x%08.8x/n" ), GetLastError(), dwErrorIn );        rstrErrorInout.Format( _T( "Error 0x%08.8x" ), dwErrorIn );    }  // else:  error formatting the message}  //*** FormatError
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:82,


示例6: Fatal

static void Fatal(DWORD dw, wchar_t* message, ...) {	void *lpDisplayBuf, *lpMsgBuf;		if(dw == 0) {		// If no return code was specified, we assume that the message		// contains a function name that failed. In that case, we retrieve		// the system error message for the last-error code		dw = GetLastError();				FormatMessage(			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS,			NULL,			dw,			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),			(wchar_t*) &lpMsgBuf,			0,			NULL		);		// Allocate our buffer for the error message.		lpDisplayBuf = (void*)LocalAlloc(			LMEM_ZEROINIT,			(lstrlenW((const wchar_t*)lpMsgBuf) + lstrlenW((const wchar_t*)message) + 47) * sizeof(wchar_t)		);		_snwprintf(			(wchar_t*)lpDisplayBuf,			LocalSize(lpDisplayBuf) / sizeof(wchar_t),			L"FATAL: %s failed with error %d: %s",			message,			dw,			lpMsgBuf		);	} else {		// Otherwise, we assume that the error message is a format string.		va_list args = NULL;				// Allocate buffer for our resulting format string.		lpMsgBuf = (void*)LocalAlloc(			LMEM_ZEROINIT,			(lstrlenW((const wchar_t*)message) + 8) * sizeof(wchar_t)		);		_snwprintf(			(wchar_t*)lpMsgBuf,			LocalSize(lpMsgBuf) / sizeof(wchar_t),			L"FATAL: %s",			message		);				// Might as well use the maximum allowed buffer, since there's no way I know of the		// get the size of the resulting buff.		lpDisplayBuf = (void*)LocalAlloc(LMEM_ZEROINIT, 4096 * sizeof(wchar_t));		memset(lpDisplayBuf, 0, 4096 * sizeof(wchar_t));		va_start(args, lpMsgBuf);		_vsnwprintf(			(wchar_t*)lpDisplayBuf,			4096,			lpMsgBuf,			args		);		va_end(args);	}	MessageBoxW(NULL, (const wchar_t*)lpDisplayBuf, L"Fatal Error", MB_OK | MB_ICONERROR);	LocalFree(lpMsgBuf);	LocalFree(lpDisplayBuf);	ExitProcess(dw); }
开发者ID:daleathan,项目名称:depends-launcher,代码行数:67,


示例7: winMWExtWMWindowProc

//.........这里部分代码省略.........        winDebug ("winMWExtWMWindowProc - WM_*KEYUP/n");#endif        /* Pass the message to the root window */        SendMessage (hwndScreen, message, wParam, lParam);        return 0;    case WM_HOTKEY:#if CYGMULTIWINDOW_DEBUG        winDebug ("winMWExtWMWindowProc - WM_HOTKEY/n");#endif        /* Pass the message to the root window */        SendMessage (hwndScreen, message, wParam, lParam);        return 0;    case WM_PAINT:        /* BeginPaint gives us an hdc that clips to the invalidated region */        hdcUpdate = BeginPaint (hwnd, &ps);        /* Try to copy from the shadow buffer */        if (!BitBlt (hdcUpdate,                     ps.rcPaint.left, ps.rcPaint.top,                     ps.rcPaint.right - ps.rcPaint.left,                     ps.rcPaint.bottom - ps.rcPaint.top,                     pRLWinPriv->hdcShadow,                     ps.rcPaint.left, ps.rcPaint.top,                     SRCCOPY))        {            LPVOID lpMsgBuf;            /* Display a fancy error message */            FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |                           FORMAT_MESSAGE_FROM_SYSTEM |                           FORMAT_MESSAGE_IGNORE_INSERTS,                           NULL,                           GetLastError (),                           MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),                           (LPTSTR) &lpMsgBuf,                           0, NULL);            ErrorF ("winMWExtWMWindowProc - BitBlt failed: %s/n",                    (LPSTR)lpMsgBuf);            LocalFree (lpMsgBuf);        }        /* EndPaint frees the DC */        EndPaint (hwnd, &ps);        break;    case WM_ACTIVATE:#if CYGMULTIWINDOW_DEBUG        winDebug ("winMWExtWMWindowProc - WM_ACTIVATE/n");#endif        if (LOWORD(wParam) != WA_INACTIVE)        {            if (winIsInternalWMRunning(pScreenInfo))            {#if 0                /* Raise the window to the top in Z order */                wmMsg.msg = WM_WM_RAISE;                if (fWMMsgInitialized)                    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);#endif                /* Tell our Window Manager thread to activate the window */
开发者ID:miettal,项目名称:armadillo420_standard_linux314,代码行数:67,


示例8: PrepareEnvOptions

int ScriptController::Execute(){	PrepareEnvOptions(NULL);	PrepareArgs();	int iExitCode = 0;	int pipein;#ifdef CHILD_WATCHDOG	bool bChildConfirmed = false;	while (!bChildConfirmed && !m_bTerminated)	{#endif#ifdef WIN32	// build command line	char* szCmdLine = NULL;	if (m_szArgs)	{		char szCmdLineBuf[2048];		int iUsedLen = 0;		for (const char** szArgPtr = m_szArgs; *szArgPtr; szArgPtr++)		{			snprintf(szCmdLineBuf + iUsedLen, 2048 - iUsedLen, "/"%s/" ", *szArgPtr);			iUsedLen += strlen(*szArgPtr) + 3;		}		szCmdLineBuf[iUsedLen < 2048 ? iUsedLen - 1 : 2048 - 1] = '/0';		szCmdLine = szCmdLineBuf;	}	else	{		szCmdLine = m_szCmdLine;	}		// create pipes to write and read data	HANDLE hReadPipe, hWritePipe;	SECURITY_ATTRIBUTES SecurityAttributes;	memset(&SecurityAttributes, 0, sizeof(SecurityAttributes));	SecurityAttributes.nLength = sizeof(SecurityAttributes);	SecurityAttributes.bInheritHandle = TRUE;	CreatePipe(&hReadPipe, &hWritePipe, &SecurityAttributes, 0);	SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);	STARTUPINFO StartupInfo;	memset(&StartupInfo, 0, sizeof(StartupInfo));	StartupInfo.cb = sizeof(StartupInfo);	StartupInfo.dwFlags = STARTF_USESTDHANDLES;	StartupInfo.hStdInput = 0;	StartupInfo.hStdOutput = hWritePipe;	StartupInfo.hStdError = hWritePipe;	PROCESS_INFORMATION ProcessInfo;	memset(&ProcessInfo, 0, sizeof(ProcessInfo));	char* szEnvironmentStrings = m_environmentStrings.GetStrings();	BOOL bOK = CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, szEnvironmentStrings, m_szWorkingDir, &StartupInfo, &ProcessInfo);	if (!bOK)	{		DWORD dwErrCode = GetLastError();		char szErrMsg[255];		szErrMsg[255-1] = '/0';		if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErrCode, 0, szErrMsg, 255, NULL))		{			PrintMessage(Message::mkError, "Could not start %s: %s", m_szInfoName, szErrMsg);		}		else		{			PrintMessage(Message::mkError, "Could not start %s: error %i", m_szInfoName, dwErrCode);		}		if (!Util::FileExists(m_szScript))		{			PrintMessage(Message::mkError, "Could not find file %s", m_szScript);		}		free(szEnvironmentStrings);		return -1;	}	free(szEnvironmentStrings);	debug("Child Process-ID: %i", (int)ProcessInfo.dwProcessId);	m_hProcess = ProcessInfo.hProcess;	// close unused "write" end	CloseHandle(hWritePipe);	pipein = _open_osfhandle((intptr_t)hReadPipe, _O_RDONLY);#else	int p[2];	int pipeout;	// create the pipe	if (pipe(p))	{//.........这里部分代码省略.........
开发者ID:ta264,项目名称:nzbget_svn,代码行数:101,


示例9: defined

void SocketLayer::SetSocketOptions( SOCKET listenSocket){	int sock_opt = 1;	// // On Vista, can get WSAEACCESS (10013)	/*	if ( setsockopt( listenSocket, SOL_SOCKET, SO_REUSEADDR, ( char * ) & sock_opt, sizeof ( sock_opt ) ) == -1 )	{	#if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG) && !defined(X360)	DWORD dwIOError = GetLastError();	LPVOID messageBuffer;	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,	NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language	( LPTSTR ) & messageBuffer, 0, NULL );	// something has gone wrong here...	RAKNET_DEBUG_PRINTF( "setsockopt(SO_REUSEADDR) failed:Error code - %d/n%s", dwIOError, messageBuffer );	//Free the buffer.	LocalFree( messageBuffer );	#endif	}	*/	// This doubles the max throughput rate	sock_opt=1024*256;	setsockopt(listenSocket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );	// Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails.	sock_opt=0;	setsockopt(listenSocket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) );#if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3)	// This doesn't make much difference: 10% maybe	// Not supported on console 2	sock_opt=1024*16;	setsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );#endif	/*	#ifdef _WIN32		unsigned long nonblocking = 1;		ioctlsocket( listenSocket, FIONBIO, &nonblocking );	#elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)                                                                                                            	#else		fcntl( listenSocket, F_SETFL, O_NONBLOCK );	#endif	*/	// Set broadcast capable	sock_opt=1;	if ( setsockopt( listenSocket, SOL_SOCKET, SO_BROADCAST, ( char * ) & sock_opt, sizeof( sock_opt ) ) == -1 )		{#if defined(_WIN32) && defined(_DEBUG)		DWORD dwIOError = GetLastError();		// On Vista, can get WSAEACCESS (10013)		// See http://support.microsoft.com/kb/819124		// http://blogs.msdn.com/wndp/archive/2007/03/19/winsock-so-exclusiveaddruse-on-vista.aspx		// http://msdn.microsoft.com/en-us/library/ms740621(VS.85).aspx#if !defined(_XBOX) && !defined(X360)		LPVOID messageBuffer;		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language			( LPTSTR ) & messageBuffer, 0, NULL );		// something has gone wrong here...		RAKNET_DEBUG_PRINTF( "setsockopt(SO_BROADCAST) failed:Error code - %d/n%s", dwIOError, messageBuffer );		//Free the buffer.		LocalFree( messageBuffer );#endif#endif		}}
开发者ID:Hamcha,项目名称:facilitator,代码行数:71,


示例10: winTopLevelWindowProc

//.........这里部分代码省略.........        /* BeginPaint gives us an hdc that clips to the invalidated region */        hdcUpdate = BeginPaint(hwnd, &ps);        /* Avoid the BitBlt's if the PAINTSTRUCT is bogus */        if (ps.rcPaint.right == 0 && ps.rcPaint.bottom == 0 &&                ps.rcPaint.left == 0 && ps.rcPaint.top == 0) {            EndPaint(hwnd, &ps);            return 0;        }#ifdef XWIN_GLX_WINDOWS        if (pWinPriv->fWglUsed) {            /*               For regions which are being drawn by GL, the shadow framebuffer doesn't have the               correct bits, so don't bitblt from the shadow framebuffer               XXX: For now, just leave it alone, but ideally we want to send an expose event to               the window so it really redraws the affected region...             */            ValidateRect(hwnd, &(ps.rcPaint));        }        else#endif            /* Try to copy from the shadow buffer */            if (!BitBlt(hdcUpdate,                        ps.rcPaint.left, ps.rcPaint.top,                        ps.rcPaint.right - ps.rcPaint.left,                        ps.rcPaint.bottom - ps.rcPaint.top,                        s_pScreenPriv->hdcShadow,                        ps.rcPaint.left + pWin->drawable.x,                        ps.rcPaint.top + pWin->drawable.y, SRCCOPY)) {                LPVOID lpMsgBuf;                /* Display a fancy error message */                FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |                              FORMAT_MESSAGE_FROM_SYSTEM |                              FORMAT_MESSAGE_IGNORE_INSERTS,                              NULL,                              GetLastError(),                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),                              (LPTSTR) &lpMsgBuf, 0, NULL);                ErrorF("winTopLevelWindowProc - BitBlt failed: %s/n",                       (LPSTR) lpMsgBuf);                LocalFree(lpMsgBuf);            }        /* EndPaint frees the DC */        EndPaint(hwnd, &ps);        return 0;    case WM_MOUSEMOVE:        /* Unpack the client area mouse coordinates */        ptMouse.x = GET_X_LPARAM(lParam);        ptMouse.y = GET_Y_LPARAM(lParam);        /* Translate the client area mouse coordinates to screen coordinates */        ClientToScreen(hwnd, &ptMouse);        /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */        ptMouse.x -= GetSystemMetrics(SM_XVIRTUALSCREEN);        ptMouse.y -= GetSystemMetrics(SM_YVIRTUALSCREEN);        /* We can't do anything without privates */        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)            break;
开发者ID:sheldonrobinson,项目名称:VcXsrv,代码行数:66,


示例11: DisplayErrorMsg

VOIDDisplayErrorMsg(    LONG msgId,    ...    )/*++Routine Description:    This routine displays the error message correspnding to    the error indicated by msgId.Arguments:    msgId - the errorId. This is either the Win32 status code or the message ID.Return Value:    None--*/{        va_list args;    LPWSTR lpMsgBuf;    va_start( args, msgId );        if (FormatMessage(        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,        NULL,        MSG_ERROR,        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language        (LPWSTR) &lpMsgBuf,        0,        NULL        ))    {        wprintf( L"%ws", lpMsgBuf );        LocalFree( lpMsgBuf );    }    if (FormatMessage(        (msgId >= MSG_FIRST_MESSAGE_ID ? FORMAT_MESSAGE_FROM_HMODULE :                                        FORMAT_MESSAGE_FROM_SYSTEM)         | FORMAT_MESSAGE_ALLOCATE_BUFFER,        NULL,        msgId,        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language        (LPWSTR) &lpMsgBuf,        0,        &args        ))    {        wprintf( L" %ws /n", (LPSTR)lpMsgBuf );        LocalFree( lpMsgBuf );    } else {        if (NtDllHandle == INVALID_HANDLE_VALUE) {            NtDllHandle = GetModuleHandle( L"NTDLL" );        }                if (FormatMessage(            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,            (LPVOID)NtDllHandle,            msgId,            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language            (LPWSTR) &lpMsgBuf,            0,            &args))        {            wprintf( L" %ws /n", (LPSTR)lpMsgBuf );            LocalFree( lpMsgBuf );        } else {            wprintf( L"Unable to format message for id %x - %x/n", msgId, GetLastError( ));        }    }        va_end( args );}
开发者ID:Nevermore2015,项目名称:ndas4windows,代码行数:79,


示例12: switch

void win_socket::get_error_text(char* buf, size_t buf_size){    char* msg;     char  msgbuf[64];    switch(errcode) {       case ok:        msg = "ok";        break;      case not_opened:        msg = "socket not opened";        break;      case bad_address:         msg = "bad address";        break;      case connection_failed:         msg = "exceed limit of attempts of connection to server";        break;      case broken_pipe:        msg = "connection is broken";        break;       case invalid_access_mode:        msg = "invalid access mode";        break;      default: #ifndef PHAR_LAP        {          int   len;#if defined(_WINCE) || defined(UNICODE)          wchar_t cnvBuf[CNV_BUF_SIZE];          FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,                        NULL,                        errcode,                        0,                        cnvBuf,                        CNV_BUF_SIZE-1,                        NULL);          cnvBuf[CNV_BUF_SIZE-1] = '/0';          len = wcstombs(buf, cnvBuf, buf_size);#else          len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,                              NULL,                              errcode,                              0,                              buf,                              (DWORD)buf_size-1,                              NULL);#endif          if (len == 0) {               sprintf(msgbuf, "unknown error code %u", errcode);              msg = msgbuf;          } else {               return;          }        }#else        sprintf(msgbuf, "System error code: %u", errcode);        msg = msgbuf;#endif    }    strncpy(buf, msg, buf_size-1);    buf[buf_size-1] = '/0';}
开发者ID:nakijun,项目名称:FusionDB,代码行数:63,


示例13: GETOBJREF

//.........这里部分代码省略.........// Old object ref tcp:/neo0001.$z123/18650:ObjectName//				strcpy(objRef, srvrObjRef);				pCheck = objRef + 5;				if ((pIpAddress = strtok(pCheck, ".")) != NULL)				{					strtok(NULL, "/");					if ((pPortNumber = strtok(NULL, ":")) != NULL)					{						if ((pObjectName = strtok(NULL, ":")) != NULL)						{							sprintf( fwsrvrObjRef, "tcp:%s/%s:%s", pIpAddress,pPortNumber,pObjectName);						}					}					srvrSegName = pIpAddress;				}			}		}		pConnection->setGetObjRefHdlOutput(fwsrvrObjRef, dialogueId, dataSource, &userSid, &versionList, srvrNodeId, srvrProcessId, timestamp);		break;	case odbcas_ASSvc_GetObjRefHdl_ASParamError_exn_ :	// Added check to see if No CPUs or Invalid CPU list are set for MXCS server to start then return 	// error back to client as param error then parse the error in client to return proper error message.		pCheck = strstr(exception_.u.ASParamError.ErrorText, "CPU" );		if (pCheck == NULL)			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PROGRAM_ERROR, exception_.exception_nr,				exception_.u.ASParamError.ErrorText);		else			pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_NO_SRVR_AVAILABLE, 0,				exception_.u.ASNotAvailable.ErrorText);		break;		case odbcas_ASSvc_GetObjRefHdl_LogonUserFailure_exn_ :		PVOID lpMsgBuf;		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,				NULL,				exception_.u.LogonUserFailure.errorCode,				MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // Default language				(LPTSTR) &lpMsgBuf,				0,				NULL);		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_UNABLE_TO_LOGON,			exception_.u.LogonUserFailure.errorCode,			 (char *)lpMsgBuf);		LocalFree(lpMsgBuf);		break;	case odbcas_ASSvc_GetObjRefHdl_ASNotAvailable_exn_ :		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_ASSOC_SRVR_NOT_AVAILABLE, 0,			exception_.u.ASNotAvailable.ErrorText);		break;	case odbcas_ASSvc_GetObjRefHdl_DSNotAvailable_exn_:		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_DS_NOT_AVAILABLE,0L,				exception_.u.DSNotAvailable.ErrorText);		break;	case odbcas_ASSvc_GetObjRefHdl_PortNotAvailable_exn_:		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PORT_NOT_AVAILABLE);		break;	case odbcas_ASSvc_GetObjRefHdl_InvalidUser_exn_:		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_28_000);		break;	case odbcas_ASSvc_GetObjRefHdl_ASTimeout_exn_ :		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_S1_T00);		break;	case odbcas_ASSvc_GetObjRefHdl_ASNoSrvrHdl_exn_ :		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_NO_SRVR_AVAILABLE, 0,			exception_.u.ASNotAvailable.ErrorText);		break;
开发者ID:AlexPeng19,项目名称:incubator-trafodion,代码行数:67,


示例14: WSA_perror

//.........这里部分代码省略.........            break;        case WSAESTALE:            usMsgNum = IDS_WSAESTALE;            break;        case WSAEINVAL:            usMsgNum = IDS_WSAEINVAL;            break;        case WSAEMFILE:            usMsgNum = IDS_WSAEMFILE;            break;        case WSAELOOP:            usMsgNum = IDS_WSAELOOP;            break;        case WSAEREMOTE:            usMsgNum = IDS_WSAEREMOTE;            break;        case WSAENOTSOCK:            usMsgNum = IDS_WSAENOTSOCK;            break;        case WSAEADDRNOTAVAIL:            usMsgNum = IDS_WSAEADDRNOTAVAIL;            break;        case WSAEADDRINUSE:            usMsgNum = IDS_WSAEADDRINUSE;            break;        case WSAEAFNOSUPPORT:            usMsgNum = IDS_WSAEAFNOSUPPORT;            break;        case WSAESOCKTNOSUPPORT:            usMsgNum = IDS_WSAESOCKTNOSUPPORT;            break;        case WSAEPROTONOSUPPORT:            usMsgNum = IDS_WSAEPROTONOSUPPORT;            break;        case WSAENOBUFS:            usMsgNum = IDS_WSAENOBUFS;            break;        case WSAETIMEDOUT:            usMsgNum = IDS_WSAETIMEDOUT;            break;        case WSAEISCONN:            usMsgNum = IDS_WSAEISCONN;            break;        case WSAENOTCONN:            usMsgNum = IDS_WSAENOTCONN;            break;        case WSAENOPROTOOPT:            usMsgNum = IDS_WSAENOPROTOOPT;            break;        case WSAECONNRESET:            usMsgNum = IDS_WSAECONNRESET;            break;        case WSAECONNABORTED:            usMsgNum = IDS_WSAECONNABORTED;            break;        case WSAENETDOWN:            usMsgNum = IDS_WSAENETDOWN;            break;        case WSAENETRESET:            usMsgNum = IDS_WSAENETRESET;            break;        case WSAECONNREFUSED:            usMsgNum = IDS_WSAECONNREFUSED;            break;        case WSAEHOSTDOWN:            usMsgNum = IDS_WSAEHOSTDOWN;            break;        case WSAEHOSTUNREACH:            usMsgNum = IDS_WSAEHOSTUNREACH;            break;        case WSAEPROTOTYPE:            usMsgNum = IDS_WSAEPROTOTYPE;            break;        case WSAEOPNOTSUPP:            usMsgNum = IDS_WSAEOPNOTSUPP;            break;        case WSAENETUNREACH:            usMsgNum = IDS_WSAENETUNREACH;            break;        case WSAETOOMANYREFS:            usMsgNum = IDS_WSAETOOMANYREFS;            break;        default:            return(0);    }    if (!(msglen = FormatMessage(               FORMAT_MESSAGE_FROM_HMODULE,               (LPVOID)SockModuleHandle,               usMsgNum,               0L,               perr,               MAX_MSGTABLE,               NULL))) {        return(0);    }    fprintf(stderr, "-> %s:%s/n", yourmsg, perr);    return(1);}
开发者ID:mingpen,项目名称:OpenNT,代码行数:101,


示例15: main

int main(int argc, char *argv[]){    char *filepath, *cmd;    char fn[SIZE];    int i;    int fd, fd_start, fd_end, fd_ret, fd_stdout, fd_stderr;    time_t now;#ifdef _WINDOWS    char full_cmd[SIZE];    TCHAR w_cmd[SIZE];    STARTUPINFO si;    PROCESS_INFORMATION pi;    DWORD ret;    LPVOID lpMsgBuf;    char msg[SIZE];#else    pid_t pid;    int ret;#endif    if (argc != 3) {        fprintf(stderr, "%s output_filepath command/n", argv[0]);        return -1;    }    filepath = argv[1];    cmd = argv[2];    ret = 127;    fd = -1;    fd_start = -1;    fd_end = -1;    fd_ret = -1;    fd_stdout = -1;    fd_stderr = -1;    i = 0;    while (ext[i] != NULL) {        sprintf(fn, "%s.%s", filepath, ext[i]);        fd = open(fn, O_WRONLY | O_BINARY | O_TRUNC);        if (fd < 0) {            fprintf(stderr, "%s: %s/n", fn, strerror(errno));            return -1;        }        if (i == 0)            fd_start = fd;        else if (i == 1)            fd_end = fd;        else if (i == 2)            fd_ret = fd;        else if (i == 3)            fd_stdout = fd;        else if (i == 4)            fd_stderr = fd;        else            close(fd);        i++;    }    fflush(stdout);    fflush(stderr);    dup2(fd_stdout, 1);    dup2(fd_stderr, 2);    now = time(NULL);    if (write(fd_start, &now, sizeof(now)) < 0)        fprintf(stderr, "fd_start: %s/n", strerror(errno));    close(fd_start);#ifdef _WINDOWS    ZeroMemory(full_cmd, sizeof(full_cmd));    ZeroMemory(w_cmd, sizeof(w_cmd));    ZeroMemory(&si, sizeof(si));    si.cb = sizeof(si);    ZeroMemory(&pi, sizeof(pi));    SetLastError(NO_ERROR);    sprintf(full_cmd, "cmd /q /k /"%s/" & exit !errorlevel!", cmd);    MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED, full_cmd,                        strlen(full_cmd), w_cmd, sizeof(w_cmd));    if (0 == CreateProcess(NULL,        /* no module name (use command line) */                           w_cmd,       /* name of app to launch */                           NULL,        /* default process security attributes */                           NULL,        /* default thread security attributes */                           TRUE,        /* do not inherit handles from the parent */                           0,   /* normal priority */                           NULL,        /* use the same environment as the parent */                           NULL,        /* launch in the current directory */                           &si, /* startup information */                           &pi  /* process information stored upon return */        )) {        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |                      FORMAT_MESSAGE_FROM_SYSTEM |                      FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),                      (LPTSTR) & lpMsgBuf, 0, NULL);        WideCharToMultiByte(CP_ACP, 0, (LPTSTR) lpMsgBuf, -1, msg, SIZE,                            NULL, NULL);        fprintf(stderr, "failed to create process for [%s]: %s", cmd, msg);        LocalFree(lpMsgBuf);//.........这里部分代码省略.........
开发者ID:hatta0713,项目名称:jobarranger,代码行数:101,


示例16: htons

SOCKET SocketLayer::CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048 ){	(void) blockingSocket;	int ret;	SOCKET listenSocket;	sockaddr_in listenerSocketAddress;	// Listen on our designated Port#	listenerSocketAddress.sin_port = htons( port );#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)	listenSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_VDP );#else	listenSocket = socket( AF_INET, SOCK_DGRAM, 0 );#endif	if ( listenSocket == (SOCKET) -1 )	{#if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG)		DWORD dwIOError = GetLastError();		LPVOID messageBuffer;		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language			( LPTSTR ) & messageBuffer, 0, NULL );		// something has gone wrong here...		RAKNET_DEBUG_PRINTF( "socket(...) failed:Error code - %d/n%s", dwIOError, messageBuffer );		//Free the buffer.		LocalFree( messageBuffer );#endif		return (SOCKET) -1;	}	SetSocketOptions(listenSocket);	// Fill in the rest of the address structure	listenerSocketAddress.sin_family = AF_INET;	if (forceHostAddress && forceHostAddress[0])	{//		printf("Force binding %s:%i/n", forceHostAddress, port);		listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress );	}	else	{//		printf("Binding any on port %i/n", port);		listenerSocketAddress.sin_addr.s_addr = INADDR_ANY;	}	// bind our name to the socket	ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) );	if ( ret <= -1 )	{#if defined(_WIN32) && !defined(_XBOX) && !defined(X360)		DWORD dwIOError = GetLastError();		if (dwIOError==10048)		{			if (sleepOn10048==0)				return (SOCKET) -1;			// Vista has a bug where it returns WSAEADDRINUSE (10048) if you create, shutdown, then rebind the socket port unless you wait a while first.			// Wait, then rebind			RakSleep(100);			closesocket(listenSocket);			listenerSocketAddress.sin_port = htons( port );			listenSocket = socket( AF_INET, SOCK_DGRAM, 0 );			if ( listenSocket == (SOCKET) -1 )				return false;			SetSocketOptions(listenSocket);			// Fill in the rest of the address structure			listenerSocketAddress.sin_family = AF_INET;			if (forceHostAddress && forceHostAddress[0])				listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress );			else				listenerSocketAddress.sin_addr.s_addr = INADDR_ANY;			// bind our name to the socket			ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) );			if ( ret >= 0 )				return listenSocket;		}		dwIOError = GetLastError();		LPVOID messageBuffer;		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language			( LPTSTR ) & messageBuffer, 0, NULL );		// something has gone wrong here...		RAKNET_DEBUG_PRINTF( "bind(...) failed:Error code - %d/n%s", (unsigned int) dwIOError, (char*) messageBuffer );		//Free the buffer.		LocalFree( messageBuffer );#elif (defined(__GNUC__)  || defined(__GCCXML__) || defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)) && !defined(__WIN32)		switch (ret)		{		case EBADF:			RAKNET_DEBUG_PRINTF("bind(): sockfd is not a valid descriptor./n"); break;#if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3)		case ENOTSOCK:			RAKNET_DEBUG_PRINTF("bind(): Argument is a descriptor for a file, not a socket./n"); break;//.........这里部分代码省略.........
开发者ID:Hamcha,项目名称:facilitator,代码行数:101,


示例17: s_perror

//.........这里部分代码省略.........        case EADDRINUSE:        usMsgNum = IDS_EADDRINUSE ;            break;        case EAFNOSUPPORT:        usMsgNum = IDS_EAFNOSUPPORT ;            break;        case ESOCKTNOSUPPORT:        usMsgNum = IDS_ESOCKTNOSUPPORT ;            break;        case EPROTONOSUPPORT:        usMsgNum = IDS_EPROTONOSUPPORT ;            break;        case ENOBUFS:        usMsgNum = IDS_ENOBUFS ;            break;        case ETIMEDOUT:        usMsgNum = IDS_ETIMEDOUT ;            break;        case EISCONN:        usMsgNum = IDS_EISCONN ;            break;        case ENOTCONN:        usMsgNum = IDS_ENOTCONN ;            break;        case ENOPROTOOPT:        usMsgNum = IDS_ENOPROTOOPT ;            break;        case ECONNRESET:        usMsgNum = IDS_ECONNRESET ;            break;        case ECONNABORT:        usMsgNum = IDS_ECONNABORT ;            break;        case ENETDOWN:        usMsgNum = IDS_ENETDOWN ;            break;        case ECONNREFUSED:        usMsgNum = IDS_ECONNREFUSED ;            break;        case EHOSTUNREACH:        usMsgNum = IDS_EHOSTUNREACH ;            break;        case EPROTOTYPE:        usMsgNum = IDS_EPROTOTYPE ;            break;        case EOPNOTSUPP:        usMsgNum = IDS_EOPNOTSUPP ;            break;        case ESUBNET:        usMsgNum = IDS_ESUBNET ;            break;        case ENETNOLNK:        usMsgNum = IDS_ENETNOLNK ;            break;        case EBADIOCTL:        usMsgNum = IDS_EBADIOCTL ;            break;        case ERESOURCE:        usMsgNum = IDS_ERESOURCE ;            break;        case EPROTUNR:        usMsgNum = IDS_EPROTUNR ;            break;        case EPORTUNR:        usMsgNum = IDS_EPORTUNR ;            break;        case ENETUNR:        usMsgNum = IDS_ENETUNR ;            break;        case EPACKET:        usMsgNum = IDS_EPACKET ;            break;        case ETYPEREG:        usMsgNum = IDS_ETYPEREG ;            break;        case ENOTINIT:        usMsgNum = IDS_ENOTINIT ;            break;        default:            if (WSA_perror(yourmsg, lerrno)) {                return;            }        usMsgNum = IDS_UNKNOWN ;            break;    }    if (!(msglen = FormatMessage(               FORMAT_MESSAGE_FROM_HMODULE,               (LPVOID)SockModuleHandle,               usMsgNum,               0L,               perr,               MAX_MSGTABLE,               NULL))) {    return;    }    fprintf(stderr, "> %s:%s/n", yourmsg, perr);    return;}
开发者ID:mingpen,项目名称:OpenNT,代码行数:101,


示例18: Error

void Error (const char *error, ...){  va_list argptr;  char	text[4096];  va_start (argptr,error);  vsprintf (text, error,argptr);  va_end (argptr);  strcat( text, "/n" );#if defined (__linux__) || defined (__APPLE__)  if (errno != 0)  {    strcat( text, "errno: " );    strcat( text, strerror (errno));    strcat( text, "/n");  }#endif#ifdef WIN32  if (GetLastError() != 0)  {    LPVOID lpMsgBuf;    FormatMessage(       FORMAT_MESSAGE_ALLOCATE_BUFFER |       FORMAT_MESSAGE_FROM_SYSTEM |       FORMAT_MESSAGE_IGNORE_INSERTS,      0,      GetLastError(),      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language      (LPTSTR) &lpMsgBuf,      0,      0       );    strcat( text, "GetLastError: " );    /*    Gtk will only crunch 0<=char<=127    this is a bit hackish, but I didn't find useful functions in win32 API for this    http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516    */    TCHAR *scan, *next = (TCHAR*)lpMsgBuf;    do    {      scan = next;      text[strlen(text)+1] = '/0';      if ((scan[0] >= 0) && (scan[0] <= 127))        text[strlen(text)] = char(scan[0]);      else        text[strlen(text)] = '?';      next = CharNext(scan);    } while (next != scan);    strcat( text, "/n");    LocalFree( lpMsgBuf );  }#endif#if 0  // we need to have a current context to call glError()  if (g_glwindow_globals.d_glBase != 0)  {    // glGetError .. can record several errors, clears after calling    //++timo TODO: be able to deal with several errors if necessary, for now I'm just warning about pending error messages    // NOTE: forget that, most boards don't seem to follow the OpenGL standard    GLenum iGLError = glGetError();    if (iGLError != GL_NO_ERROR)    {      // use our own gluErrorString      strcat( text, "gluErrorString: " );      strcat( text, (char*)gluErrorString( iGLError ) );      strcat( text, "/n" );    }  }#endif  strcat (text, "An unrecoverable error has occured./n");  ERROR_MESSAGE(text);  // force close logging if necessary	Sys_LogFile(false);  _exit (1);}
开发者ID:ChunHungLiu,项目名称:GtkRadiant,代码行数:84,


示例19: RakAssert

int SocketLayer::SendTo( SOCKET s, const char *data, int length, unsigned int binaryAddress, unsigned short port, unsigned short remotePortRakNetWasStartedOn_PS3 ){	RakAssert(length<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE);	RakAssert(port!=0);	if (slo)	{		SystemAddress sa(binaryAddress,port);		return slo->RakNetSendTo(s,data,length,sa);	}	if ( s == (SOCKET) -1 )	{		return -1;	}	int len=0;	if (remotePortRakNetWasStartedOn_PS3!=0)	{		len = SendTo_PS3Lobby(s,data,length,binaryAddress,port, remotePortRakNetWasStartedOn_PS3);	}	else	{#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)		len = SendTo_360(s,data,length,0,0,binaryAddress,port);#else		len = SendTo_PC(s,data,length,binaryAddress,port);#endif	}	if ( len != -1 )		return 0;#if defined(_WIN32) && !defined(_WIN32_WCE)	DWORD dwIOError = WSAGetLastError();	if ( dwIOError == WSAECONNRESET )	{#if defined(_DEBUG)		RAKNET_DEBUG_PRINTF( "A previous send operation resulted in an ICMP Port Unreachable message./n" );#endif	}	else if ( dwIOError != WSAEWOULDBLOCK && dwIOError != WSAEADDRNOTAVAIL)	{#if defined(_WIN32) && !defined(_XBOX) && !defined(X360) && defined(_DEBUG)		LPVOID messageBuffer;		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language			( LPTSTR ) & messageBuffer, 0, NULL );		// something has gone wrong here...		RAKNET_DEBUG_PRINTF( "sendto failed:Error code - %d/n%s", dwIOError, messageBuffer );		//Free the buffer.		LocalFree( messageBuffer );#endif	}	return dwIOError;#endif	return 1; // error}
开发者ID:Hamcha,项目名称:facilitator,代码行数:66,


示例20: ProcessError

    /*     * Write error message to Event Log, console or pop-up window     *     * If useGetLastError is 1, the last error returned from GetLastError()     * is appended to pszMessage, separated by a ": ".     *     * eventLogType:                 MessageBox equivalent:     *      * EVENTLOG_INFORMATION_TYPE     MB_ICONASTERISK     * EVENTLOG_WARNING_TYPE         MB_ICONEXCLAMATION     * EVENTLOG_ERROR_TYPE           MB_ICONSTOP     *      */VOIDProcessError (WORD eventLogType, LPCTSTR pszMessage, int useGetLastError, int quiet){  LPTSTR pErrorMsgTemp = NULL;  HANDLE hEventSource = NULL;  TCHAR pszMessageFull[MAX_STR_SIZE]; /* Combined pszMessage and GetLastError */  /*   * If useGetLastError enabled, generate text from GetLastError() and append to   * pszMessageFull   */  if (useGetLastError) {  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |		 FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),		 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),        (LPTSTR) & pErrorMsgTemp, 0, NULL);    _snprintf (pszMessageFull, sizeof(pszMessageFull), "%s: %s", pszMessage, pErrorMsgTemp);    if (pErrorMsgTemp) {      LocalFree (pErrorMsgTemp);      pErrorMsgTemp = NULL;    }  }  else {    _snprintf (pszMessageFull, sizeof(pszMessageFull), "%s", pszMessage);  }    hEventSource = RegisterEventSource (NULL, app_name);  if (hEventSource != NULL) {    pErrorMsgTemp = pszMessageFull;        if (ReportEvent (hEventSource,           eventLogType,           0,          DISPLAY_MSG,	/* To Just output the text to event log */          NULL,           1,           0,           &pErrorMsgTemp,           NULL)) {    }    else {      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |          FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),          MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),          (LPTSTR) & pErrorMsgTemp, 0, NULL);            fprintf(stderr,"Could NOT lot to Event Log.  Error returned from ReportEvent(): %s/n",pErrorMsgTemp);      if (pErrorMsgTemp) {        LocalFree (pErrorMsgTemp);        pErrorMsgTemp = NULL;      }    }    DeregisterEventSource (hEventSource);    }      if (quiet) {    fprintf(stderr,"%s/n",pszMessageFull);      }      else {    switch (eventLogType) {      case EVENTLOG_INFORMATION_TYPE:        MessageBox (NULL, pszMessageFull, app_name, MB_ICONASTERISK);        break;      case EVENTLOG_WARNING_TYPE:        MessageBox (NULL, pszMessageFull, app_name, MB_ICONEXCLAMATION);        break;      case EVENTLOG_ERROR_TYPE:        MessageBox (NULL, pszMessageFull, app_name, MB_ICONSTOP);        break;      default:        MessageBox (NULL, pszMessageFull, app_name, EVENTLOG_WARNING_TYPE);        break;      }    }    LocalFree (pErrorMsgTemp);  }
开发者ID:DYFeng,项目名称:infinidb,代码行数:91,


示例21: createErrorMessage

/** outTitle should be set before the call */static void createErrorMessage(    const char*         expression,    const std::string&  message,    const char*         filename,    int                 lineNumber,    std::string&        outTitle,    std::string&        outMessage) {    std::string le = "";    const char* newline = "/n";    #ifdef G3D_WIN32        newline = "/r/n";        // The last error value.  (Which is preserved across the call).        DWORD lastErr = GetLastError();            // The decoded message from FormatMessage        LPTSTR formatMsg = NULL;        if (NULL == formatMsg) {            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |                          FORMAT_MESSAGE_IGNORE_INSERTS |                          FORMAT_MESSAGE_FROM_SYSTEM,                            NULL,                            lastErr,                            0,                            (LPTSTR)&formatMsg,                            0,                            NULL);        }        // Make sure the message got translated into something.        LPTSTR realLastErr;        if (NULL != formatMsg) {            realLastErr = formatMsg;        } else {            realLastErr = _T("Last error code does not exist.");        }		if (lastErr != 0) {	        le = G3D::format("Last Error (0x%08X): %s/r/n/r/n", lastErr, (LPCSTR)realLastErr);		}        // Get rid of the allocated memory from FormatMessage.        if (NULL != formatMsg) {            LocalFree((LPVOID)formatMsg);        }        char modulePath[MAX_PATH];        GetModuleFileNameA(NULL, modulePath, MAX_PATH);        const char* moduleName = strrchr(modulePath, '//');        outTitle = outTitle + string(" - ") + string(moduleName ? (moduleName + 1) : modulePath);    #endif    // Build the message.    outMessage =        G3D::format("%s%s%sExpression: %s%s%s:%d%s%s%s",                  message.c_str(), newline, newline, expression, newline,                  filename, lineNumber, newline, newline, le.c_str());}
开发者ID:luaman,项目名称:g3d-cvs,代码行数:66,


示例22: _al_show_native_file_dialog

bool _al_show_native_file_dialog(ALLEGRO_DISPLAY *display,   ALLEGRO_NATIVE_DIALOG *fd){   OPENFILENAME ofn;   ALLEGRO_DISPLAY_WIN *win_display;   int flags = 0;   bool ret;   char buf[4096] = "";   ALLEGRO_USTR *filter_string = NULL;   win_display = (ALLEGRO_DISPLAY_WIN *)display;   if (fd->flags & ALLEGRO_FILECHOOSER_FOLDER) {      return select_folder(win_display, fd);   }   /* Selecting a file. */   memset(&ofn, 0, sizeof(OPENFILENAME));   ofn.lStructSize = sizeof(OPENFILENAME);   ofn.hwndOwner = (win_display) ? win_display->window : NULL;   /* Create filter string. */   if (fd->fc_patterns) {      filter_string = create_filter_string(fd->fc_patterns);      ofn.lpstrFilter = al_cstr(filter_string);   }   else {      /* List all files by default. */      ofn.lpstrFilter = "All Files/0*.*/0/0";   }   ofn.lpstrFile = buf;   ofn.nMaxFile = sizeof(buf);   if (fd->fc_initial_path) {      ofn.lpstrInitialDir =         al_path_cstr(fd->fc_initial_path, ALLEGRO_NATIVE_PATH_SEP);   }   if (fd->title)      ofn.lpstrTitle = al_cstr(fd->title);   flags |= OFN_NOCHANGEDIR | OFN_EXPLORER;   if (fd->flags & ALLEGRO_FILECHOOSER_SAVE) {      flags |= OFN_OVERWRITEPROMPT;   }   else {      flags |= (fd->flags & ALLEGRO_FILECHOOSER_FILE_MUST_EXIST) ? OFN_FILEMUSTEXIST : 0;   }   flags |= (fd->flags & ALLEGRO_FILECHOOSER_MULTIPLE) ? OFN_ALLOWMULTISELECT : 0;   flags |= (fd->flags & ALLEGRO_FILECHOOSER_SHOW_HIDDEN) ? 0x10000000 : 0; // NOTE: 0x10000000 is FORCESHOWHIDDEN   ofn.Flags = flags;   if (flags & OFN_OVERWRITEPROMPT) {      ret = GetSaveFileName(&ofn);   }   else {      ret = GetOpenFileName(&ofn);   }   al_ustr_free(filter_string);   if (!ret) {      DWORD err = GetLastError();      if (err != ERROR_SUCCESS) {         char buf[1000];         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, buf, sizeof(buf), NULL);         ALLEGRO_ERROR("al_show_native_file_dialog failed: %s/n", buf);      }      return false;   }   if (flags & OFN_ALLOWMULTISELECT) {      int i;      /* Count number of file names in buf. */      fd->fc_path_count = 0;      i = skip_nul_terminated_string(buf);      while (1) {         if (buf[i] == '/0') {            fd->fc_path_count++;            if (buf[i+1] == '/0')               break;         }         i++;      }   }   else {      fd->fc_path_count = 1;   }   if (fd->fc_path_count == 1) {      fd->fc_paths = al_malloc(sizeof(void *));      fd->fc_paths[0] = al_create_path(buf);   }   else {      int i, p;      /* If multiple files were selected, the first string in buf is the       * directory name, followed by each of the file names terminated by NUL.       */      fd->fc_paths = al_malloc(fd->fc_path_count * sizeof(void *));//.........这里部分代码省略.........
开发者ID:dradtke,项目名称:battlechess,代码行数:101,


示例23: run_postreceive_multi

/** * Run the postreceive script on list of received files */void run_postreceive_multi(struct group_list_t *group, char *const *files,                           int count){    char **params;    char gid_str[10];    char gid_param[] = "-I";    int i;    if (!strcmp(postreceive, "")) {        return;    }    params = safe_calloc(count + 4, sizeof(char *));    snprintf(gid_str, sizeof(gid_str), "%08X", group->group_id);    params[0] = postreceive;    params[1] = gid_param;    params[2] = gid_str;    for (i = 0; i < count; i++) {        params[i+3] = files[i];    }    params[count+4-1] = NULL;    if (log_level >= 2) {        cglog2(group, "Running postreceive: %s", postreceive);        for (i = 1; i < count + 3; i++) {            sclog2(" %s", params[i]);        }        slog2("");    }#ifdef WINDOWS    {        char cmdline[0x8000];  // Windows max command line length        char cmdexe[MAXPATHNAME];        int too_long, rval, is_cmd;        strcpy(cmdline, "");        if ((!strncmp(&postreceive[strlen(postreceive)-4], ".cmd", 4)) ||                (!strncmp(&postreceive[strlen(postreceive)-4], ".bat", 4))) {            is_cmd = 1;            if (!GetEnvironmentVariable("SystemRoot", cmdexe, sizeof(cmdexe))) {                char errbuf[300];                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),                              0, errbuf, sizeof(errbuf), NULL);                glog0(group, "Error getting sysroot: (%d) %s",                             GetLastError(), errbuf);                free(params);                return;            }            strcat(cmdexe, "//system32//cmd.exe");            strcat(cmdline, "/c /"");        } else {            is_cmd = 0;        }        for (too_long = 0, i = 0; i < count + 3; i++) {            int size = 0x8000 - strlen(cmdline);            if (size <= (int)strlen(params[i]) + 4) {                too_long = 1;                break;            }            // Quote everything except -I {group_id}            if (i == 1 || i == 2) {                strcat(cmdline, params[i]);                strcat(cmdline," ");            } else {                strcat(cmdline, "/"");                strcat(cmdline, params[i]);                strcat(cmdline,"/" ");            }        }        if (is_cmd) {            strcat(cmdline, "/"");        }        if (!too_long) {            STARTUPINFO startup_info;            PROCESS_INFORMATION proc_info;            GetStartupInfo(&startup_info);            rval = CreateProcess(is_cmd ? cmdexe : postreceive, cmdline,                NULL, NULL, 0, CREATE_NO_WINDOW, NULL, NULL,                &startup_info, &proc_info);            if (!rval) {                char errbuf[300];                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),                              0, errbuf, sizeof(errbuf), NULL);                glog0(group, "Error running script: (%d) %s",                             GetLastError(), errbuf);            }        }    }#else    {        pid_t pid;        if ((pid = fork()) == -1) {//.........这里部分代码省略.........
开发者ID:No9,项目名称:uftp,代码行数:101,


示例24: uscsetlock

// 0 if it can't get the resource, 1 if it can// -1 if failint vrpn_Semaphore::condP(){    int iRetVal = 1;#ifdef sgi    if (fUsingLock) {        // don't spin at all        iRetVal = uscsetlock(l, 0);        if (iRetVal <= 0) {            perror("vrpn_Semaphore::condP: uscsetlock:");            return -1;        }    }    else {        iRetVal = uscpsema(ps);        if (iRetVal <= 0) {            perror("vrpn_Semaphore::condP: uscpsema:");            return -1;        }    }#elif defined(_WIN32)    switch (WaitForSingleObject(hSemaphore, 0)) {    case WAIT_OBJECT_0:        // got the resource        break;    case WAIT_TIMEOUT:        // resource not free        iRetVal = 0;        break;    case WAIT_ABANDONED:        ALL_ASSERT(0, "vrpn_Semaphore::condP: thread holding resource died");        return -1;        break;    case WAIT_FAILED:        // get error info from windows (from FormatMessage help page)        LPVOID lpMsgBuf;        FormatMessage(            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,            GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),            // Default language            (LPTSTR)&lpMsgBuf, 0, NULL);        fprintf(stderr,            "Semaphore::condP: error waiting for resource, "            "WIN32 WaitForSingleObject call caused the following error: %s",            (LPTSTR)lpMsgBuf);        // Free the buffer.        LocalFree(lpMsgBuf);        return -1;        break;    default:        ALL_ASSERT(0, "vrpn_Semaphore::p: unknown return code");        return -1;    }#else    // Posix by default    iRetVal = sem_trywait(semaphore);    if (iRetVal == 0) {        iRetVal = 1;    }    else if (errno == EAGAIN) {        iRetVal = 0;    }    else {        perror("vrpn_Semaphore::condP: ");        iRetVal = -1;    }#endif    return iRetVal;}
开发者ID:ChristophHaag,项目名称:vrpn,代码行数:71,


示例25: move_to_backup

/** * For the current file in a group, move the existing file to * the appropriate backup directory, if it exists. * In the event of a failure, delete the original file */void move_to_backup(struct group_list_t *group){    stat_struct statbuf;    char backup_file[MAXBACKUPPATHNAME], *trim_name;    int len;    if (lstat_func(group->fileinfo.filepath, &statbuf) == -1) {        return;    }    if (backupcnt == 0) {        clear_path(group->fileinfo.filepath, group);        return;    }#ifdef WINDOWS    if ((group->fileinfo.filepath[1] == ':') &&            (group->fileinfo.filepath[2] == '//')) {        trim_name = &group->fileinfo.filepath[3];    } else {        trim_name = group->fileinfo.filepath;    }#else    trim_name = group->fileinfo.filepath;#endif    len = snprintf(backup_file, sizeof(backup_file), "%s%c%s%c%s%c%s",                   backupdir[group->fileinfo.destdiridx], PATH_SEP,                   group->start_date, PATH_SEP,                   group->start_time, PATH_SEP, trim_name);    if (len >= sizeof(backup_file)) {        glog0(group, "Max pathname length exceeded for backup file, deleting",                     group->fileinfo.filepath);        clear_path(group->fileinfo.filepath, group);        return;    }    clear_path(backup_file, group);    if (!create_path_to_file(group, backup_file)) {        glog0(group, "Error creating path to backup file");        clear_path(group->fileinfo.filepath, group);    }#ifdef WINDOWS    if (!MoveFile(group->fileinfo.filepath, backup_file)) {        char errbuf[300];        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL,                GetLastError(), 0, errbuf, sizeof(errbuf), NULL);        glog0(group, "Couldn't rename from %s to %s, deleting: (%d): %s",                group->fileinfo.filepath, backup_file, GetLastError(), errbuf);        clear_path(group->fileinfo.filepath, group);    } else {        glog2(group, "Backed up existing file to %s", backup_file);    }#else    if (rename(group->fileinfo.filepath, backup_file) == -1) {        gsyserror(group, "Couldn't rename from %s to %s, deleting",                         group->fileinfo.filepath, backup_file);        clear_path(group->fileinfo.filepath, group);    } else {        glog2(group, "Backed up existing file to %s", backup_file);    }#endif}
开发者ID:No9,项目名称:uftp,代码行数:66,


示例26: main

//__________________________________________________________________________________int main (int argc, char* argv[]){	mainArgCount = argc - 1;			#ifdef	__HYPHYMPI__		  int 		   rank, 		  			   size;		  			   			   			 		  MPI_Init	   (&argc, &argv);		  MPI_Comm_rank(MPI_COMM_WORLD, &rank);		  MPI_Comm_size(MPI_COMM_WORLD, &size);		  		  setParameter  (mpiNodeID,    (_Parameter)rank);		  setParameter	(mpiNodeCount, (_Parameter)size);		  _hy_mpi_node_rank = rank;		  		  if (rank == 0)		  {			  mpiNodesThatCantSwitch.Populate (size,1,0);		  				/* {				  char hostname[256];				  gethostname(hostname, sizeof(hostname));				  printf("PID %d on %s ready for attach/n", getpid(), hostname);				  fflush(stdout);				  //getchar ();			  }	*/	#endif			//for (long k=0; k<NSIG; k++)	//{	//	signal(k, &hyphyBreak);	//}		#ifdef	__HYPHYMPI__		  }	#endif		char 	curWd[4096],		    dirSlash = GetPlatformDirectoryChar ();	getcwd (curWd,4096);	_String baseDir (curWd), 			argFile;			baseDir=baseDir & dirSlash;	pathNames&& &baseDir;		baseDirectory = baseDir;	baseArgDir	  = baseDirectory;		_ExecutionList ex;			#ifdef _OPENMP	systemCPUCount = omp_get_max_threads();#endif	#ifdef _MINGW32_MEGA_	{		char pid[16];		snprintf (pid,16,"%u", GetCurrentProcessId());				_String pipeName = _String("////.//pipe//MEGAPipe") & pid;		printf ("Pipe name = %s/n", pipeName.sData);		if ((_HY_MEGA_Pipe = CreateFile(pipeName.sData, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)		{			char* lpMsgBuf;			FormatMessage(				FORMAT_MESSAGE_ALLOCATE_BUFFER | 				FORMAT_MESSAGE_FROM_SYSTEM |				FORMAT_MESSAGE_IGNORE_INSERTS,				NULL,				GetLastError(),				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),				(LPTSTR) &lpMsgBuf,				0, NULL );			FlagError (_String("Failed to create a pipe named '") & pipeName & "' to send data from HyPhy to MEGA. Error: "&lpMsgBuf);		}	}#endif			for (long i=1; i<argc;i++)	{		_String thisArg (argv[i]);		if (thisArg.sData[0]=='-')		{			ProcessConfigStr (thisArg);		}		else			if (thisArg.beginswith ("BASEPATH="))			{				baseArgDir = thisArg.Cut(9,-1);				if (baseArgDir.sLength)				{					if (baseArgDir.sData[baseArgDir.sLength-1]!=dirSlash)						baseArgDir = baseArgDir&dirSlash;						//.........这里部分代码省略.........
开发者ID:mdsmith,项目名称:OCLHYPHY,代码行数:101,


示例27: logg_internal

//.........这里部分代码省略.........				logg_buff->limit = logg_buff->capacity = len;			} else {				ret_val = buffer_remaining(*logg_buff);				break;			}		}		/* put msg printed out in buffer */		va_copy(tmp_valist, args);		ret_val = my_vsnprintf(buffer_start(*logg_buff), buffer_remaining(*logg_buff), fmt, tmp_valist);		va_end(tmp_valist);		/* error? repeat */	} while(unlikely(ret_val < 0 || (size_t)ret_val > buffer_remaining(*logg_buff)));	logg_buff->pos += (size_t)ret_val;	/* add errno string if wanted */	if(log_errno)	{		if(buffer_remaining(*logg_buff) < STRERROR_R_SIZE + 4)		{			size_t len = logg_buff->capacity * 2;			struct big_buff *tmp_buff = realloc(logg_buff, sizeof(*logg_buff) + len);			if(!tmp_buff)				goto no_errno;			logg_buff = tmp_buff;			logg_buff->limit = logg_buff->capacity += len;		}		*buffer_start(*logg_buff) = ':'; logg_buff->pos++;		*buffer_start(*logg_buff) = ' '; logg_buff->pos++;		{#if defined STRERROR_R_CHAR_P || defined HAVE_MTSAFE_STRERROR || WIN32 || !(defined HAVE_STRERROR_R || HAVE_DECL_STRERROR_R-0 > 0)			size_t err_str_len;# ifdef WIN32			const char *s = buffer_start(*logg_buff);			if(!(err_str_len = FormatMessage(				FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */				0, /* pointer to other source */				old_errno, /* msg id */				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* language */				buffer_start(*logg_buff), /* buffer */				buffer_remaining(*logg_buff)-1, /* size */				0 /* va_args */			))) {				s = "Unknown system error";				err_str_len = strlen(s) < buffer_remaining(*logg_buff)-2 ?				              strlen(s) : buffer_remaining(*logg_buff)-2;			}# else#  ifdef STRERROR_R_CHAR_P			/*			 * the f***ing GNU-Version of strerror_r wich returns			 * a char * to the buffer....			 * This sucks especially in conjunction with strnlen,			 * wich needs a #define __GNU_SOURCE, but conflicts			 * with this...			 */			const char *s = strerror_r(old_errno, buffer_start(*logg_buff), buffer_remaining(*logg_buff)-2);#  else			/*			 * Ol Solaris seems to have a static msgtable, so			 * strerror is threadsafe and we don't have a			 * _r version			 */			/*			 * we also simply fall into here if strerror is not thread			 * safe, but we have nothing else.			 * Since what should we do in this case... _sys_errlist
开发者ID:kaffeemonster,项目名称:g2cd,代码行数:67,


示例28: Sys_Exec

/*========================Sys_Execif waitMsec is INFINITE, completely block until the process exitsIf waitMsec is -1, don't wait for the process to exitOther waitMsec values will allow the workFn to be called at those intervals.========================*/bool Sys_Exec(	const char * appPath, const char * workingPath, const char * args, 	execProcessWorkFunction_t workFn, execOutputFunction_t outputFn, const int waitMS,	unsigned int & exitCode ) {		exitCode = 0;		SECURITY_ATTRIBUTES secAttr;		secAttr.nLength = sizeof( SECURITY_ATTRIBUTES );		secAttr.bInheritHandle = TRUE;		secAttr.lpSecurityDescriptor = NULL;		HANDLE hStdOutRead;		HANDLE hStdOutWrite;		CreatePipe( &hStdOutRead, &hStdOutWrite, &secAttr, 0 );		SetHandleInformation( hStdOutRead, HANDLE_FLAG_INHERIT, 0 );		HANDLE hStdInRead;		HANDLE hStdInWrite;		CreatePipe( &hStdInRead, &hStdInWrite, &secAttr, 0 );		SetHandleInformation( hStdInWrite, HANDLE_FLAG_INHERIT, 0 );												STARTUPINFO si;		memset( &si, 0, sizeof( si ) );		si.cb = sizeof( si );		si.hStdError = hStdOutWrite;		si.hStdOutput = hStdOutWrite;		si.hStdInput = hStdInRead;		si.wShowWindow = FALSE;		si.dwFlags |= STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;		PROCESS_INFORMATION pi;		memset ( &pi, 0, sizeof( pi ) );		if ( outputFn != NULL ) {			outputFn( va( "^2Executing Process: ^7%s/n^2working path: ^7%s/n^2args: ^7%s/n", appPath, workingPath, args ) );		} else {			outputFn = ExecOutputFn;		}		// we duplicate args here so we can concatenate the exe name and args into a single command line		const char * imageName = appPath;		char * cmdLine = NULL;		{			// if we have any args, we need to copy them to a new buffer because CreateProcess modifies			// the command line buffer.			if ( args != NULL ) {				if ( appPath != NULL ) {					int len = idStr::Length( args ) + idStr::Length( appPath ) + 1 /* for space */ + 1 /* for NULL terminator */ + 2 /* app quotes */;					cmdLine = (char*)Mem_Alloc( len, TAG_TEMP );					// note that we're putting quotes around the appPath here because when AAS2.exe gets an app path with spaces					// in the path "w:/zion/build/win32/Debug with Inlines/AAS2.exe" it gets more than one arg for the app name,					// which it most certainly should not, so I am assuming this is a side effect of using CreateProcess.					idStr::snPrintf( cmdLine, len, "/"%s/" %s", appPath, args );				} else {					int len = idStr::Length( args ) + 1;					cmdLine = (char*)Mem_Alloc( len, TAG_TEMP );					idStr::Copynz( cmdLine, args, len );				}				// the image name should always be NULL if we have command line arguments because it is already				// prefixed to the command line.				imageName = NULL;			}		}		BOOL result = CreateProcess( imageName, (LPSTR)cmdLine, NULL, NULL, TRUE, 0, NULL, workingPath, &si, &pi );		if ( result == FALSE ) {			TCHAR szBuf[1024]; 			LPVOID lpMsgBuf;			DWORD dw = GetLastError(); 			FormatMessage(				FORMAT_MESSAGE_ALLOCATE_BUFFER | 				FORMAT_MESSAGE_FROM_SYSTEM,				NULL,				dw,				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),				(LPTSTR) &lpMsgBuf,				0, NULL );			wsprintf( szBuf, "%d: %s", dw, lpMsgBuf );			if ( outputFn != NULL ) {				outputFn( szBuf );			}			LocalFree( lpMsgBuf );			if ( cmdLine != NULL ) {				Mem_Free( cmdLine );			}			return false;		} else if ( waitMS >= 0 ) {	// if waitMS == -1, don't wait for process to exit			DWORD ec = 0;			DWORD wait = 0;			char buffer[ 4096 ];//.........这里部分代码省略.........
开发者ID:Yetta1,项目名称:OpenTechBFG,代码行数:101,


示例29: switch

//.........这里部分代码省略.........							// order bindings by defined ordering in ControlAction::listOrder							std::map<int, int> orderMap;							for(InputEventController::ActionMap::iterator it = map.begin(); it != map.end(); it++)								orderMap[it->second->getListOrder()] = it->first;														// user wants to change assigned binding							int selectedIndex = SendMessage(hList, LVM_GETSELECTIONMARK, 0, 0);							if(selectedIndex == -1)								break; // apparently nothing is selected							setControlHash = orderMap[selectedIndex];							setControlMap = mapname;							if(pressAnyKeyDialog == NULL) {								WNDCLASSW lWinClass;								lWinClass.style = CS_DBLCLKS;								lWinClass.lpfnWndProc = PressKeyDialogFunc;								lWinClass.cbClsExtra = 0;								lWinClass.cbWndExtra = 0;								lWinClass.hInstance = GetInstanceHandle();								lWinClass.hIcon = NULL;								lWinClass.hCursor = LoadCursor(NULL, IDC_ARROW);								lWinClass.hbrBackground = (HBRUSH) COLOR_APPWORKSPACE + 1;								lWinClass.lpszMenuName = NULL;								lWinClass.lpszClassName = L"IDD_PRESS_ANY_KEY";								lReturnValue = RegisterClassW(&lWinClass);								// set HWND for when we get called back								preferencesDialog = pWindow;								RECT size = {0};								GetWindowRect(app->GetWindowHandle(), &size);								SetCursorPos(size.left + 110, size.top + 80); // move to center of new window								pressAnyKeyDialog = CreateWindowW(									L"IDD_PRESS_ANY_KEY",									PACKAGE_NAME_L,									(WS_POPUPWINDOW | WS_VISIBLE),									size.left + 30,									size.top + 30,									160,									100,									app->GetWindowHandle(),									NULL,									GetInstanceHandle(),									this);								if(pressAnyKeyDialog == NULL) { // report error if necessary									DWORD err = GetLastError();									LPVOID errMsg;														FormatMessage(										FORMAT_MESSAGE_ALLOCATE_BUFFER |										FORMAT_MESSAGE_FROM_SYSTEM,										NULL,										err,										MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),										(LPTSTR) &errMsg,										0, NULL);									MessageBox(NULL, (const char*) errMsg, "AIEEE", MB_ICONERROR | MB_APPLMODAL | MB_OK);									LocalFree(errMsg);								}							} else {								// put focus back to already existing window								EnableWindow(pWindow, false);								EnableWindow(pressAnyKeyDialog, true);							}						}						break;				}			}			break;		case WM_NOTIFY:			switch (((NMHDR FAR *) pLParam)->code) {				case PSN_APPLY:					pressAnyKeyDialog = NULL;					// reload controller					app->ReloadController();					cfg->Save();					break;				case PSN_RESET:					pressAnyKeyDialog = NULL;					break;				case PSN_KILLACTIVE:					// for receipt of PSN_APPLY					SetWindowLong(pWindow, DWL_MSGRESULT, FALSE);					break;			}	}	return lReturnValue;}
开发者ID:espes,项目名称:hoverrace,代码行数:101,



注:本文中的FormatMessage函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ FormatMessageA函数代码示例
C++ FormatMagickString函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。