void NamedPipe::Initialize() { SECURITY_ATTRIBUTES attr; attr.bInheritHandle = TRUE; attr.nLength = sizeof(SECURITY_ATTRIBUTES); attr.lpSecurityDescriptor = NULL; mHandle = CreateFileA( mName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &attr, OPEN_EXISTING, 0, NULL); if (mHandle == INVALID_HANDLE) { mHandle = CreateNamedPipeA( mName.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 65536, 65536, NMPWAIT_WAIT_FOREVER, &attr); if (mHandle == INVALID_HANDLE) { throw NamedPipeException(GetLastErrorString()); } else if (!ConnectNamedPipe(mHandle, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) { throw NamedPipeException(GetLastErrorString()); } } }
void CChordEaseApp::WinHelp(DWORD dwData, UINT nCmd) { //printf("dwData=%d:%d nCmd=%d\n", HIWORD(dwData), LOWORD(dwData), nCmd); CPathStr HelpPath(GetAppFolder()); HelpPath.Append(CString(m_pszAppName) + _T(".chm")); HWND hMainWnd = GetMain()->m_hWnd; UINT ResID = LOWORD(dwData); int HelpID = FindHelpID(ResID); HWND hWnd = 0; // assume failure if (HelpID) // if context help ID was found hWnd = ::HtmlHelp(hMainWnd, HelpPath, HH_HELP_CONTEXT, HelpID); if (!hWnd) { // if context help wasn't available or failed hWnd = ::HtmlHelp(hMainWnd, HelpPath, HH_DISPLAY_TOC, 0); // show contents if (!hWnd) { // if help file not found CString s; AfxFormatString1(s, IDS_APP_HELP_FILE_MISSING, HelpPath); AfxMessageBox(s); return; } } // ThreadBoost DLL boosts priority of MIDI input callbacks, but also boosts // other normal threads, including HtmlHelp's, which is counterproductive if (m_ThreadBoost.IsLoaded()) { // if boosting normal priority threads DWORD ThreadID = GetWindowThreadProcessId(hWnd, NULL); // obtain set info access to HtmlHelp's thread and set its priority to normal CSafeHandle hThread(OpenThread(THREAD_SET_INFORMATION, FALSE, ThreadID)); if (hThread == NULL || !::SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL)) AfxMessageBox(GetLastErrorString()); } m_HelpInit = TRUE; }
// Deletes a directory filename, returns true on success bool DeleteDir(const std::string& filename) { INFO_LOG(COMMON, "DeleteDir: directory %s", filename.c_str()); // check if a directory if (!IsDirectory(filename)) { ERROR_LOG(COMMON, "DeleteDir: Not a directory %s", filename.c_str()); return false; } #ifdef _WIN32 if (::RemoveDirectory(UTF8ToTStr(filename).c_str())) return true; ERROR_LOG(COMMON, "DeleteDir: RemoveDirectory failed on %s: %s", filename.c_str(), GetLastErrorString().c_str()); #else if (rmdir(filename.c_str()) == 0) return true; ERROR_LOG(COMMON, "DeleteDir: rmdir failed on %s: %s", filename.c_str(), LastStrerrorString().c_str()); #endif return false; }
// renames file srcFilename to destFilename, returns true on success bool Rename(const std::string& srcFilename, const std::string& destFilename) { INFO_LOG(COMMON, "Rename: %s --> %s", srcFilename.c_str(), destFilename.c_str()); #ifdef _WIN32 auto sf = UTF8ToTStr(srcFilename); auto df = UTF8ToTStr(destFilename); // The Internet seems torn about whether ReplaceFile is atomic or not. // Hopefully it's atomic enough... if (ReplaceFile(df.c_str(), sf.c_str(), nullptr, REPLACEFILE_IGNORE_MERGE_ERRORS, nullptr, nullptr)) return true; // Might have failed because the destination doesn't exist. if (GetLastError() == ERROR_FILE_NOT_FOUND) { if (MoveFile(sf.c_str(), df.c_str())) return true; } ERROR_LOG(COMMON, "Rename: MoveFile failed on %s --> %s: %s", srcFilename.c_str(), destFilename.c_str(), GetLastErrorString().c_str()); #else if (rename(srcFilename.c_str(), destFilename.c_str()) == 0) return true; ERROR_LOG(COMMON, "Rename: rename failed on %s --> %s: %s", srcFilename.c_str(), destFilename.c_str(), LastStrerrorString().c_str()); #endif return false; }
CClient :: ~CClient( ) { if( closesocket( m_sckClient ) == SOCKET_ERROR ) UTIL_LogPrint( "client error: Closing Socket (error %s)\n", GetLastErrorString( ) ); else if( gbDebug ) UTIL_LogPrint( "client: Socket Closed\n" ); }
CVideoExchange::CVideoExchange(LPCTSTR strLoadFile) { COINIT eInit = COINIT_MULTITHREADED; CoInitializeEx(0,eInit); if (0 != strLoadFile) m_sLoadFile = strLoadFile; HRESULT hr = m_pDocument.CreateInstance(L"MSXML.FreeThreadedDOMDocument"); CString se; GetLastErrorString(se); ASSERT(ERROR_SUCCESS == hr); m_pstrNodeText = new char[8192]; // m_sBitRate; // m_sMPEGFormat; // m_sCardId; m_nRoomId = -1; // m_sFileName; // m_odtStart; // m_odtStop; m_nDuration = -1; m_nVideoStorageServerId = -1; m_nStreamingEncoderId = -1; // m_sSessionId; // m_sSessionName; // m_sDisplayName; }
int lutil_srv_remove(LPCTSTR lpszServiceName, LPCTSTR lpszBinaryPathName) { SC_HANDLE schSCManager, schService; fprintf( stderr, "The installed path is %s.\n", lpszBinaryPathName ); if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT|SC_MANAGER_CREATE_SERVICE)) != NULL ) { if ((schService = OpenService(schSCManager, lpszServiceName, DELETE)) != NULL) { if ( DeleteService(schService) == TRUE) { CloseServiceHandle(schService); CloseServiceHandle(schSCManager); return(1); } else { fprintf( stderr, "DeleteService() failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() ); fprintf( stderr, "The %s service has not been removed.\n", lpszBinaryPathName); CloseServiceHandle(schService); CloseServiceHandle(schSCManager); return(0); } } else { fprintf( stderr, "OpenService() failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() ); CloseServiceHandle(schSCManager); return(0); } } else fprintf( stderr, "OpenSCManager() failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() ); return(0); }
int main(int argc, char* argv[]) { CommandLine()->CreateCmdLine( argc, argv ); const char *pDLLName = "vvis_dll.dll"; CSysModule *pModule = Sys_LoadModule( pDLLName ); if ( !pModule ) { printf( "vvis launcher error: can't load %s\n%s", pDLLName, GetLastErrorString() ); return 1; } CreateInterfaceFn fn = Sys_GetFactory( pModule ); if( !fn ) { printf( "vvis launcher error: can't get factory from %s\n", pDLLName ); Sys_UnloadModule( pModule ); return 2; } int retCode = 0; ILaunchableDLL *pDLL = (ILaunchableDLL*)fn( LAUNCHABLE_DLL_INTERFACE_VERSION, &retCode ); if( !pDLL ) { printf( "vvis launcher error: can't get IVVisDLL interface from %s\n", pDLLName ); Sys_UnloadModule( pModule ); return 3; } pDLL->main( argc, argv ); Sys_UnloadModule( pModule ); return 0; }
void CChordEaseApp::CAppEngine::OnError(LPCTSTR Msg) { CString sMsg(Msg); if (GetLastError()) sMsg += '\n' + GetLastErrorString(); AfxMessageBox(sMsg); }
/*------------------------------------------------------------------------------*/ static void _UsbResetDevice( void ) { WaitForUsbResetStatus(USB_RESET_STATUS_RESETTING); LOG(LOG_LEVEL_INFO, "_UsbResetDevice()"); PROCESS_INFORMATION pi = {0}; STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; TCHAR commandLine[256]; lstrcpy(commandLine, TEXT("ResetUsb.exe")); if (!CreateProcess(NULL, commandLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) { LOG(LOG_LEVEL_WARN, "UsbResetDevice(): CreateProcess(){reason=\"%s\"}", GetLastErrorString()); } CloseHandle(pi.hThread); // TODO(nahanaha): Check the bug that ResetUsb.exe does not exit in some cases. WaitForSingleObject(pi.hProcess, 1 * 1000); CloseHandle(pi.hProcess); // Use notification to detect that PSP is connected. // SetUsbResetStatus(USB_RESET_STATUS_OPENING); }
///Get last err informations(log the debug information) unsigned long PRE_ERR_GetLastError(const char* filePath, const char* function, int line) { PRE_ERR_GetLastError(); const char* fileName = strrchr(filePath,'\\'); Logging(filePath,function,line,GetLastErrorString()); printf("\t@ File : %s(Line:%d)\n\t@ Function : %s\n",fileName+1,line,function); return ErrCode; }
bool rename(const path & old_p, const path & new_p, bool overwrite) { DWORD flags = overwrite ? MOVEFILE_REPLACE_EXISTING : 0; bool ret = MoveFileExA(old_p.string().c_str(), new_p.string().c_str(), flags) == TRUE; if(!ret) { LogWarning << "MoveFileExA(" << old_p << ", " << new_p << ", " << flags << ") failed! " << GetLastErrorString(); } return ret; }
bool remove(const path & p) { bool succeeded = true; if(is_directory(p)) { succeeded &= RemoveDirectoryA(p.string().c_str()) == TRUE; if(!succeeded) { LogWarning << "RemoveDirectoryA(" << p << ") failed! " << GetLastErrorString(); } } else { succeeded &= DeleteFileA(p.string().c_str()) == TRUE; if(!succeeded) { LogWarning << "DeleteFileA(" << p << ") failed! " << GetLastErrorString(); } } return succeeded; }
ByteCount NamedPipe::Read(char* out, size_t size) const { DWORD n = 0; if (!ReadFile(mHandle, out, size, &n, NULL)) { throw NamedPipeException(GetLastErrorString()); } return n; }
ByteCount NamedPipe::Write(const char* in, size_t size) const { DWORD n = 0; if (!WriteFile(mHandle, in, size, &n, NULL)) { throw NamedPipeException(GetLastErrorString()); } return n; }
void CRipInfoDB::DeleteTrack( int nTrack ) { // Open file for append m_pFile = CDexOpenFile( m_strFileName, _W( "r" ) ); CUStringConvert strCnv; if ( NULL != m_pFile ) { fclose( m_pFile ); CDexCopyFile( m_strFileName, m_strFileName + _W( ".bak") ); CString test( GetLastErrorString() ); m_pFile = CDexOpenFile( m_strFileName + _W( ".bak"), _W( "r" ) ); FILE* pFileOut = CDexOpenFile( m_strFileName, _W( "w+" ) ); while( ( !feof( m_pFile ) ) && ( pFileOut != NULL ) ) { TCHAR lpszLine[ 1024 ] = {'\0',}; int nCurrentTrack; // Clear string memset( lpszLine, 0x00, sizeof( lpszLine ) ); // Read the next line from the file _fgetts( lpszLine, sizeof( lpszLine ), m_pFile ); nCurrentTrack= _ttoi( &lpszLine[ 1 ] ); if ( nCurrentTrack != nTrack ) { _fputts( lpszLine, pFileOut ); } } fclose( m_pFile ); m_pFile = NULL; fclose( pFileOut ); m_pFile = NULL; //::DeleteFile( strCnv.ToT( m_strFileName ) ); //::CopyFile( strCnv.ToT( CUString( m_strFileName + _T( ".bak") ) ) , strCnv.ToT( m_strFileName ), FALSE ); CDexDeleteFile( m_strFileName + _W( ".bak") ); } if ( m_pFile ) { fclose( m_pFile ); m_pFile = NULL; } }
void HttpRequest::FetchGravatarForEmail() { unsigned char ehash[MD5LEN]; { char email[1024]; DWORD d; size_t len; if (WideCharToMultiByte(CP_UTF8, 0, m_target.c_str(), -1, email, sizeof(email), NULL, NULL) == 0) { ReportStatus(KHERR_ERROR, L"Can't convert email address to UTF-8", L"%s", GetLastErrorString().c_str()); return; } _strlwr_s(email, sizeof(email)); if (FAILED(StringCbLengthA(email, sizeof(email), &len))) { ReportStatus(KHERR_ERROR, L"UTF-8 email address too long", L"The email address can't be longer than 1024 characters"); return; } d = sizeof(ehash); if (KHM_FAILED(hash_data((BYTE *) email, (DWORD)len, CALG_MD5, (BYTE *) ehash, &d))) { ReportStatus(KHERR_ERROR, L"Failed to hash email address", NULL); return; } } { wchar_t resource[60]; wchar_t * tail; size_t len; int i; static const wchar_t hexdigits[] = L"0123456789abcdef"; StringCbCopyEx(resource, sizeof(resource), L"/avatar/", &tail, &len, STRSAFE_NO_TRUNCATION); for (i = 0; i < sizeof(ehash); i++) { *tail++ = hexdigits[ehash[i] >> 4]; *tail++ = hexdigits[ehash[i] & 0xf]; len -= sizeof(wchar_t) * 2; } *tail++ = L'\0'; StringCbCat(resource, sizeof(resource), L".jpg?d=404&s=128"); FetchResource(L"www.gravatar.com", resource, jpg_mimetypes); } }
/* * NET_SetErrorStringFromLastError */ void NET_SetErrorStringFromLastError( const char *function ) { const char* errorstring = GetLastErrorString(); if( function ) { NET_SetErrorString( "%s: %s", function, errorstring ); } else { NET_SetErrorString( "%s", errorstring ); } }
/*======================================================================================== FUNCTION: LBaseSock::GetListenPort() DESCRIPT: Get the listening port #. RETURN : ARGUMENT: None UPDATE : 2004/07/01, In-hyeok Paek; First work! ========================================================================================*/ int LBaseSock::GetListenPort() { CString sAddr; // IP address unsigned int nPort; // Port # if( !GetSockName( sAddr, nPort ) ) { return nPort; } else { TRACE( "Socket get peer name failed: %d - %s\n", m_nLastErr, GetLastErrorString() ); return m_nLastErr; } }
BOOL CMixOut::Ini() { if (m_bIni) { TRACE("Mix in has alreadly ini.\n"); return FALSE; } if (!OpenMixer()) { TRACE("%s.\n",GetLastErrorString()); return FALSE; }; if (!Initialize()) { TRACE("%s.\n",GetLastErrorString()); return FALSE; } m_bIni = TRUE; return TRUE; }
COysterSystem::COysterSystem(void) { HRESULT hr; hr = m_pOyster.CreateInstance("OysterClassLibrary.Oyster"); if (ERROR_SUCCESS != hr) { CString sError; GetLastErrorString(sError,(hr)); throw new CGeneralException("COysterSystem::COysterSystem", "Could not create OysterClassLibrary.Oyster object: %s",sError); } }
void cSocket::ShutdownReadWrite(void) { #ifdef _WIN32 int res = shutdown(m_Socket, SD_BOTH); #else int res = shutdown(m_Socket, SHUT_RDWR); #endif if (res != 0) { LOGWARN("%s: Error shutting down socket %d (%s): %d (%s)", __FUNCTION__, m_Socket, m_IPString.c_str(), this->GetLastError(), GetLastErrorString().c_str() ); } }
CCardVideoSystem::CCardVideoSystem() //: m_sDisplayName(_T("")) { COINIT eInit = COINIT_MULTITHREADED; CoInitializeEx(0,eInit); HRESULT hr = m_pSystem.CreateInstance("CardVideoObjects.System"); if (ERROR_SUCCESS != hr) { CString sError; GetLastErrorString(sError,(hr)); throw new CGeneralException("CCardVideoSystem::CCardVideoSystem", "Could not create CardVideoObjects.System object: %s",sError); } }
void _fatal(char* filename, unsigned long linenumber, char* message) { int res; DWORD error; char* p; error = GetLastError(); (int)fprintf(stderr, "fatal error at %s:%d -> %s\n", filename, linenumber, message); (int)fprintf(stderr, " getlasterror() -> %08x\n", error); res = GetLastErrorString(error, &p); if (res != 0) (int)fprintf(stderr, " getlasterrorstring() -> %s\n", p); exit(1); }
bool create_directory(const path & p) { if(p.empty()) { return true; } bool ret = CreateDirectoryA(p.string().c_str(), NULL) == TRUE; if(!ret) { int lastError = GetLastError(); ret = lastError == ERROR_ALREADY_EXISTS; if(!ret) { LogWarning << "CreateDirectoryA(" << p << ", NULL) failed! " << GetLastErrorString(); } } return ret; }
// copies file source_path to destination_path, returns true on success bool Copy(const std::string& source_path, const std::string& destination_path) { INFO_LOG(COMMON, "Copy: %s --> %s", source_path.c_str(), destination_path.c_str()); #ifdef _WIN32 if (CopyFile(UTF8ToTStr(source_path).c_str(), UTF8ToTStr(destination_path).c_str(), FALSE)) return true; ERROR_LOG(COMMON, "Copy: failed %s --> %s: %s", source_path.c_str(), destination_path.c_str(), GetLastErrorString().c_str()); return false; #else std::ifstream source{source_path, std::ios::binary}; std::ofstream destination{destination_path, std::ios::binary}; destination << source.rdbuf(); return source.good() && destination.good(); #endif }
void cSocket::SetNonBlocking(void) { #ifdef _WIN32 u_long NonBlocking = 1; int res = ioctlsocket(m_Socket, FIONBIO, &NonBlocking); #else int NonBlocking = 1; int res = ioctl(m_Socket, FIONBIO, (char *)&NonBlocking); #endif if (res != 0) { LOGERROR("Cannot set socket to non-blocking. This would make the server deadlock later on, aborting.\nErr: %d, %d, %s", res, GetLastError(), GetLastErrorString().c_str() ); abort(); } }
void cSocket::CloseSocket() { #ifdef _WIN32 closesocket(m_Socket); #else // _WIN32 if (close(m_Socket) != 0) { LOGWARN("Error closing socket %d (%s): %s", m_Socket, m_IPString.c_str(), GetLastErrorString().c_str()); } #endif // else _WIN32 // Invalidate the socket so that this object can be re-used for another connection m_Socket = INVALID_SOCKET; }
static void lua_pushlasterr( lua_State* L, const char* lpszFunction ) { DWORD dw; int iLenMsg; char* lpMsgBuf = GetLastErrorString( &dw, &iLenMsg ); if ( lpszFunction == NULL ) { lua_pushstring( L, lpMsgBuf ); } else { UINT uBytes = ( iLenMsg + lstrlenA( lpszFunction ) + 40 ) * sizeof(char); char* lpDisplayBuf = (char*)::LocalAlloc( LMEM_ZEROINIT, uBytes ); sprintf( lpDisplayBuf, "%s failed with error %d: %s", lpszFunction, dw, lpMsgBuf ); lua_pushstring( L, lpDisplayBuf ); ::LocalFree( lpDisplayBuf ); } ::LocalFree( lpMsgBuf ); }
static void EvaluateExpressionAndPrintResult(HWND hText, char *buffer) { int error; long line_length; line_length = strlen(buffer); error = EvaluateExpressions((char *)buffer, line_length, 0); if (error == 0) { /*Print the number in user specified format*/ PrintResult(hText, *fExpressionResult); } else { char *error_string; error_string = GetLastErrorString(); AppendText(hText, NEWLINE); AppendText(hText, error_string); } AddToExperssionHistory(buffer); }