bool OverwriteDlg::_SetStaticText(Window &Wnd, CTSTRING &tsFileName) { bool r = false; FILESIZE fs; if (FileGetSize(tsFileName, fs)) { FILETIMES ft; if (FileGetTime(tsFileName, ft)) { /* * Set the text of the static control as follows: * * [size in bytes] [formatted size] * [created date] * [modified date] */ TSTRING tsTemp; TSTRING tsFormatBytes = _GetNumberFormat(fs.ui64Bytes); sprintf(tsTemp, _T("%s Bytes (%s)\nCreated: %s\nModified: %s"), tsFormatBytes.c_str(), fs.tsStrFmt.c_str(), ft.tsLongCreated.c_str(), ft.tsLongModified.c_str()); Wnd.SetWindowText(tsTemp); r = true; } } return r; }
TSTRING Replace( const TSTRING& orignStr, const TSTRING& oldStr, const vector<TSTRING>&vc ) { size_t pos = 0; TSTRING tempStr = orignStr; TSTRING::size_type newStrLen; TSTRING::size_type oldStrLen = oldStr.length(); int i=0; while(true) { pos = tempStr.find(oldStr, pos); if (pos == TSTRING::npos) break; TSTRING s=vc.at(i); s = _T("\'")+s +_T("\'"); newStrLen= s.length(); tempStr.replace(pos, oldStrLen, s); pos += newStrLen; i++; } return tempStr; }
void MakeFile( TSTRING& strNameMakeMe ) { try { iFSServices* pFSServices = iFSServices::GetInstance(); ASSERT( pFSServices ); pFSServices->MakeTempFilename( strNameMakeMe ); std::string strA; for( TSTRING::iterator i = strNameMakeMe.begin(); i != strNameMakeMe.end(); i++ ) { char ach[6]; ASSERT( MB_CUR_MAX <= 6 ); int n = wctomb( ach, *i ); ASSERT( n != -1 ); for( int j = 0; j < n; j++ ) strA += ach[j]; } TOFSTREAM file( strA.c_str() ); ASSERT( file ); file.close(); } catch( eFSServices e ) { ASSERT( false ); } catch( ... ) { ASSERT( false ); } }
bool cUnixFSServices::GetExecutableFilename(TSTRING& strFullPath, const TSTRING& strFilename) const { bool fGotName = false; if (strFilename.empty()) return false; // if there is a slash in the filename, it's absolute or relative to cwd if (TSTRING::npos != strFilename.find(_T('/'))) { // if absolute path if (strFilename[0] == _T('/')) { strFullPath = strFilename; fGotName = true; } else // is relative path; find path from cwd { fGotName = FullPath(strFullPath, strFilename); } } else // it's just a filename: should be found in path { fGotName = util_PathFind(strFullPath, strFilename); TSTRING strFP; if (fGotName && FullPath(strFP, strFullPath)) strFullPath = strFP; } return (fGotName); }
Handle<Value> Statement::GetFieldValueByIndex(const Arguments& args) { Statement* pStatement = ObjectWrap::Unwrap<Statement>(args.This()); HandleScope scope; int index = args[0]->Int32Value(); Sqlite3_XX::VARIANT var = pStatement->pRecord->GetFieldValue(index); if (var.vt == Sqlite3_XX::VT_BSTR) { TSTRING value = var.bstrVal; #ifdef OS_WIN32 return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(value.c_str()).c_str())); #elif defined OS_LINUX return scope.Close(String::New(value.c_str())); #endif } else if (var.vt == Sqlite3_XX::VT_I4) { return scope.Close(Integer::New(var.intVal)); } else if (var.vt == Sqlite3_XX::VT_R8) { return scope.Close(Number::New(var.dblVal)); } return Undefined(); }
bool cEncoder::AllTestsRunOnEncodedString( const TSTRING& s ) const { TSTRING::const_iterator cur = s.begin(); // pointer to working position in s const TSTRING::const_iterator end = s.end(); // end of s TSTRING::const_iterator first = end; // identifies beginning of current character TSTRING::const_iterator last = end; // identifies end of current character // while get next char (updates cur) while( cCharUtil::PopNextChar( cur, end, first, last ) ) { sack_type::const_iterator atE; for( atE = m_encodings.begin(); atE != m_encodings.end(); atE++ ) { if( (*atE)->NeedsEncoding( first, last ) ) { return false; } } } return true; }
/// <summary> /// <para name='Name'>SLog::getDateTimeString</para> /// <para name='Purpose'>Return a formatted date time string</para> /// </summary> /// <param name='logFormat'>indicate whether to return the date time string in log format or decoration format</param> /// <returns>a formatted date/time string</returns> /// <remarks> /// <para name='Notes'></para> /// <para name='Author'>Kenn Guilstorf</para> /// <para name='LastModified'>2015-10-26</para> /// </remarks> TSTRING SLog::getDateTimeString(bool logFormat) { TSTRING retValue; TSTRING strFormat; TCHAR* chBuffer = new TCHAR[50]; SYSTEMTIME st; if (logFormat) { strFormat = TSTRING(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d | ")); } else { strFormat = TSTRING(_T(".%04d%02d%02d.%02d%02d%02d%03d")); } GetLocalTime(&st); SPRINTF(chBuffer, 50, strFormat.c_str(), (int)st.wYear, (int)st.wMonth, (int)st.wDay, (int)st.wHour, (int)st.wMinute, (int)st.wSecond, (int)st.wMilliseconds); retValue = TSTRING(chBuffer); return retValue; }
////////////////////////////////////////////////////////////////////////////////// // Function name : util_RemoveLastPathElement // Description : // effectively pops off a path element from the end, except for the root dir, where it does nothing // it removes any slashes before and after the element // ///root//foo/ -> leaves "///root" ("foo" is strElem) // ///root -> leaves "" ("root" is strElem) // // -> leaves "" ("" is strElem) // // Return type : void // Argument : TSTRING& strPath // Argument : TSTRING& strElem ///////////////////////////////////////////////////////////////////////////////// void util_RemoveLastPathElement(TSTRING& strPath, TSTRING& strElem) { // remove all trailing separators util_RemoveTrailingSeps(strPath); // find the last separator TSTRING::size_type lastSep = strPath.rfind(TW_SLASH); // if separator was found, take all chars after it if (lastSep != TSTRING::npos) { strElem = strPath.substr(lastSep + 1); strPath.resize(lastSep + 1); } else // no seps in name, take whole string { // last element strElem = strPath; strPath.erase(); } // remove all trailing separators util_RemoveTrailingSeps(strPath); }
//////////////////////////////////////////////////////////////////////////////// // Function name : util_RemoveDuplicateSeps // Description : // takes all adjacent slashes and replaces them with a single slash // ///root//foo -> /root/foo // rel//foo/// -> rel/foo/ // // Return type : void // Argument : TSTRING& strPath /////////////////////////////////////////////////////////////////////////////// void util_RemoveDuplicateSeps(TSTRING& strPath) { bool fLastCharWasSep = false; TSTRING::iterator iter = strPath.begin(); while (iter != strPath.end()) { bool fErasedChar = false; // if we've found a char that's not '/', then it's not the root if (*iter == TW_SLASH) { // if this char is a duplicate sep, erase it if (fLastCharWasSep) { iter = strPath.erase(iter); fErasedChar = true; } fLastCharWasSep = true; } else { fLastCharWasSep = false; } // don't go past end of string (could happen with erase) if (!fErasedChar) iter++; } }
/////////////////////////////////////////////////////////////////////////////// // LookupArgInfo /////////////////////////////////////////////////////////////////////////////// bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const { arg = _T(""); alias = _T(""); cHashTableIter<TSTRING, cArgInfo> iter(mArgTable); for(iter.SeekBegin(); ! iter.Done(); iter.Next()) { if(iter.Val().mId == argId) { TSTRING str = iter.Key(); if((str.length() > 0) && (str[0] == _T('-'))) { // this is the alias! alias = (str.c_str() + 1); } else { // this is the arg... arg = str; } } } return ((! arg.empty()) || (! alias.empty())); }
void CameraControlsDlg::_DoZeroAccumulator(void) { TSTRING tsMsg; sprintf(tsMsg, _T("Are you sure you want") _T(" to zero the step accumulator and") _T(" global frame count?\n\n") _T("Frame count is currently: %d\n"), *m_pdwFrameCount); if (IDYES == MessageBox(m_hWnd, tsMsg.c_str(), _T("FURR - Confirm Accumulator Reset"), MB_YESNO | MB_ICONQUESTION)) { if (!m_AMSComm.Camera_ResetAccumulator()) { _ThrowAMSError(); } else { *m_pdwFrameCount = 0UL; m_pParent->Output(FURR_OT_INFORMATION, _T("CameraControls:") _T("Set step accumulator and frame count to zero")); } } }
/////////////////////////////////////////////////////////////////////////////// // DisplayStringToFCOName /////////////////////////////////////////////////////////////////////////////// bool cFSNameTranslator::DisplayStringToFCOName( const TSTRING& strC, cFCOName& name ) const { TSTRING str = strC; const TCHAR dq = _T('\"'); // do a little error checking. must have at least '""' if( str.size() < 1 ) return false; if( dq != str[0] ) return false; if( dq != str[str.size() - 1] ) return false; // get rid of beginning and trailing quote str = str.substr( 1, str.size() - 2 ); // // undo funky wide char encoding // cDisplayEncoder e( cDisplayEncoder::ROUNDTRIP ); if( ! e.Decode( str ) ) return false; // give to cFCOName name = str; return true; }
/////////////////////////////////////////////////////////////////////////////// // IsObjectEncrypted /////////////////////////////////////////////////////////////////////////////// bool cTWUtil::IsObjectEncrypted(const TCHAR* objFileName, const cFileHeaderID& fhid, const TSTRING& errorMsg) { bool fEncrypted = false; cDebug d("IsObjectEncrypted"); d.TraceDebug(_T("Reading from file %s\n"), objFileName); try { cFileArchive arch; arch.OpenRead(objFileName); cFileHeader fileHeader; cSerializerImpl fhSer(arch, cSerializerImpl::S_READ, objFileName); fileHeader.Read(&fhSer); // check for a mismatched header if (fileHeader.GetID() != fhid) ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE)); // switch on the type of encoding... if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { fEncrypted = true; } else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED) { fEncrypted = false; } else // unknown encoding... ThrowAndAssert(eSerializerInputStreamFmt(_T(""), objFileName, eSerializer::TY_FILE)); } catch (eArchive& e) { // Note: Output to TCERR is O.K. here, it is documented that this is what this function does TSTRING msg = e.GetMsg(); if (!msg.empty()) msg += _T("\n"); msg += errorMsg; cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags())); ThrowAndAssert(ePoly()); } catch (eSerializer& e) { // Note: Output to TCERR is O.K. here, it is documented that this is what this function does TSTRING msg = e.GetMsg(); if (!msg.empty()) msg += _T("\n"); msg += errorMsg; cTWUtil::PrintErrorMsg(ePoly(e.GetID(), msg, e.GetFlags())); ThrowAndAssert(ePoly()); } return (fEncrypted); }
static void PrintIter(const iFCOIter* pIter, cDebug& d) { TSTRING str; for(; ! pIter->Done(); pIter->Next()) { str += pIter->FCO()->GetName().AsString().c_str(); str += _T(" "); } d.TraceDebug(_T("%s\n"), str.c_str()); }
/// <summary> /// <para name='Name'>SLog::openLog</para> /// <para name='Purpose'>Open a log for output</para> /// </summary> /// <param name='szFullPathToLog'>the full path to the log file to open</param> /// <param name='makeUnique'>Whether to append a date/time stamp to the file name</param> /// <returns>S_OK if successful, failure if it failed</returns> /// <remarks> /// <para name='Notes'></para> /// <para name='Author'>Kenn Guilstorf</para> /// <para name='LastModified'>2015-10-26</para> /// </remarks> HRESULT SLog::openLog(TSTRING szFullPathToLog, bool makeUnique) { HRESULT hrRetVal = S_OK; TSTRING szFullLogPath = TSTRING(); // If we're trying to open when a log is already open... // Let's flush and close the main OSTREAM first... if (NULL != m_pO) { m_pO->flush(); delete m_pO; m_pO = NULL; } // Now, close the file stream... if (NULL != m_log) { if (m_log->is_open()) { m_log->flush(); m_log->close(); delete m_log; m_log = NULL; } } // Split the path into path, name and ext hrRetVal = splitFullPath(szFullPathToLog); if (hrRetVal == ERROR_BAD_ARGUMENTS) goto EXIT; // Do we want to add date/time to the file? if (makeUnique) m_szLogFileName->append(getDateTimeString(false)); szFullLogPath.append(m_szLogFilePath->c_str()); szFullLogPath.append(m_szLogFileName->c_str()); szFullLogPath.append(m_szLogFileExt->c_str()); // Enter our critical section EnterCriticalSection(&m_CriticalSection); // Open our file stream m_log = new TOFSTREAM(szFullLogPath.c_str(), TOFSTREAM::app | TOFSTREAM::out); // Open a new output stream m_pO = new TOSTREAM(m_log->rdbuf()); // Leave our critical section LeaveCriticalSection(&m_CriticalSection); EXIT: return hrRetVal; }
/////////////////////////////////////////////////////////////////////////////// // Function name : util_FileIsExecutable // Description : file ( or file a link points to ) must be a regular // file and executable by someone // // Return type : bool // Argument : const TSTRING& strFile /////////////////////////////////////////////////////////////////////////////// bool util_FileIsExecutable(const TSTRING& strFile) { if (strFile.empty()) return false; struct stat s; if (stat(strFile.c_str(), &s) < 0) // this call handles links return false; return (S_ISREG(s.st_mode) && (s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))); // can someone execute it? }
TSTRING cCharEncoderUtil::HexValueToCharString( const TSTRING& str ) { TSTRING strOut; TSTRING::const_iterator at; for( at = str.begin(); at < str.end(); at += TCHAR_AS_HEX__IN_TCHARS ) { strOut += hex_to_char( at, at + TCHAR_AS_HEX__IN_TCHARS ); } return strOut; }
TSTRING cCharEncoderUtil::CharStringToHexValue( const TSTRING& str ) { TSTRING strOut; TSTRING::const_iterator at; for( at = str.begin(); at < str.end(); at++ ) { strOut += char_to_hex( *at ); } return strOut; }
void cUnixFSServices::ReadDir(const TSTRING& strFilename, std::vector<TSTRING>& v, bool bFullPaths) const { #else void cUnixFSServices::ReadDir(const TSTRING& strFilenameC, std::vector<TSTRING>& v, bool bFullPaths) const { TSTRING strFilename = cDevicePath::AsNative(strFilenameC); #endif //Get all the filenames DIR* dp = 0; #if defined(O_DIRECTORY) && defined(O_NOATIME) //dfd will be autoclosed by closedir(), should not be explicitly closed. int dfd = open(strFilename.c_str(), O_RDONLY | O_DIRECTORY | O_NOATIME); if (dfd > 0) dp = fdopendir(dfd); #else dp = opendir(strFilename.c_str()); #endif if (dp == NULL) { throw eFSServicesGeneric(strFilename, iFSServices::GetInstance()->GetErrString()); return; } struct dirent* d; while ((d = readdir(dp)) != NULL) { if ((strcmp(d->d_name, _T(".")) != 0) && (strcmp(d->d_name, _T("..")) != 0)) { if (bFullPaths) { //Create the full pathname TSTRING strNewName = strFilename; // get full path of dir entry util_TrailingSep(strNewName, true); strNewName += d->d_name; // save full path name v.push_back(strNewName); } else v.push_back(d->d_name); } } //Close the directory closedir(dp); }
bool cEncoder::AllIdentifiersUnique() const { TSTRING chars; for( sack_type::const_iterator atE = m_encodings.begin(); atE != m_encodings.end(); atE++ ) { TCHAR chID = (*atE)->Identifier(); if( chars.find( chID ) == TSTRING::npos ) chars += chID; else return false; } return true; }
/////////////////////////////////////////////////////////////////////////////// // MakeFileError /////////////////////////////////////////////////////////////////////////////// TSTRING cErrorUtil::MakeFileError( const TSTRING& msg, const TSTRING& fileName ) { TSTRING ret; ret = TSS_GetString( cCore, core::STR_ERR2_FILENAME ); ret.append( fileName ); ret.append( 1, _T('\n') ); if ( msg.length() > 0 ) { ret.append(msg); } return ret; }
bool CHelpDB::NewItem(CTSTRING& _sAlias, CTSTRING& sText, CTSTRING& sCreator) { MSXML::IXMLDOMElementPtr El; bool r = false; if(m_doc == 0) return false; TSTRING sAlias; { TCHAR* tsz = _tcsdup(_sAlias.c_str()); _tcsupr(tsz); sAlias = tsz; SAFE_FREE(tsz); } // Just determine if it exists. if(GetItemElement(sAlias, El, false)) { // it already exists; fail. sprintf(m_err, _T("%s already exists. If you want to change the existing entry, use !msgchange."), sAlias.c_str()); g_pLog->msg(_T("%s"), m_err.c_str()); } else { // doesn't already exist... we're golden like the shower. This time // just call GetItemElement() with bCreate set to true. if(!GetItemElement(sAlias, El, true)) { sprintf(m_err, _T("%s could not be added."), sAlias.c_str()); g_pLog->msg(_T("%s"), m_err.c_str()); } else { El->setAttribute(TAG_ALIAS, sAlias.c_str()); El->setAttribute(TAG_CREATOR, sCreator.c_str()); El->setAttribute(TAG_TEXT, sText.c_str()); El->setAttribute(TAG_USAGE, _T("0")); SYSTEMTIME st; TSTRING sTime; GetLocalTime(&st); Bin2Str(sTime, (BYTE*)&st, sizeof(st)); El->setAttribute(TAG_TIME, sTime.c_str()); g_pLog->msg(_T("New db item: %s = %s"), _sAlias.c_str(), sText.c_str()); r = true; } } return r; }
TSTRING PathConcatFile(CTSTRING &tsPath, CTSTRING &tsFile) { TSTRING r = tsPath; TSTRING::iterator it = r.end(); it--; if ((*it) != _T('\\') && (*it) != _T('/')) { r += _T("\\"); } return r + tsFile; }
void CSoundManager::LoadSound( TSTRING szFilename, TSTRING szReference, bool isMusic ) { CSGD_XAudio2* pXA = CSGD_XAudio2::GetInstance(); int newID; if( isMusic ) newID = pXA->MusicLoadSong(szFilename.c_str()); else newID = pXA->SFXLoadSound(szFilename.c_str()); SoundID newSoundID; newSoundID.first = szReference; newSoundID.second = newID; m_vSoundIDs.push_back(newSoundID); }
//////////////////////////////////////////////////////////////////////////////// // Function name : IsRoot // Description : A root path is all '/'s // // Return type : bool // Argument : const TSTRING& strPath /////////////////////////////////////////////////////////////////////////////// bool cUnixFSServices::IsRoot(const TSTRING& strPath) const { // and empty path is NOT the root path if (strPath.empty()) return false; // check to see if all characters are a slash for (TSTRING::const_iterator iter = strPath.begin(); iter != strPath.end(); iter++) { // if we've found a char that's not '/', then it's not the root path if (*iter != TW_SLASH) return false; } return true; }
//////////////////////////////////////////////////////////////////////// // Function name : cUnixFSServices::Rename // Description : Rename a file. Overwrites newname if it exists.and overwrite is true // // Returns : false if failure, true on success bool cUnixFSServices::Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool overwrite) const { #ifdef _UNICODE # error UNICODE Rename not implemented #endif // delete new file if overwriting if (overwrite) if (access(strNewName.c_str(), F_OK) == 0 && remove(strNewName.c_str()) != 0) return false; if (rename(strOldName.c_str(), strNewName.c_str()) == 0) return true; // Note: errno will be set return false; }
TSTRING cSHASignature::AsStringHex() const { TSTRING ret; TCHAR stringBuffer[128]; TCHAR sigStringOut[128]; sigStringOut[0] = '\0'; for (int i=0; i < SIG_UINT32_SIZE; ++i) { _stprintf(stringBuffer, _T("%08x"), mSHAInfo.digest[i]); _tcscat(sigStringOut, stringBuffer); } ret.append(sigStringOut); return ret; }
/////////////////////////////////////////////////////////////////////////////// // GetNoun // note -- you can only call this once after the verb (it eats the rest // of the line!) /////////////////////////////////////////////////////////////////////////////// static void GetNoun( TSTRING& noun ) { static TSTRING prevNoun; TCHAR buf[1024]; TCIN.getline( buf, 1024 ); // // find the end of the noun... // TCHAR* pStart = buf; TCHAR* end = &buf[1023]; while( IsSpace(*pStart) && (! IsEnd(*pStart)) && (pStart < end) ) pStart++; if( IsEnd( *pStart ) || (pStart >= end) ) { // no noun! noun = _T(""); return; } TCHAR* pCur = pStart; bool bQuote = false; if( *pCur == _T('\"') ) { bQuote = true; pCur++; pStart++; } while( pCur < end ) { if( (! bQuote) && IsSpace(*pCur) ) break; if( *pCur == _T('\"') && bQuote) break; pCur++; } noun.assign(pStart, (pCur - pStart)); if( noun.compare( _T("!$") ) == 0 ) { noun = prevNoun; } prevNoun = noun; }
TSTRING cHAVALSignature::AsStringHex() const { TSTRING ret; TCHAR stringBuffer[128]; TCHAR sigStringOut[128]; sigStringOut[0] = _T('\0'); for (int i=0; i < SIG_BYTE_SIZE; ++i) { _stprintf(stringBuffer, _T("%02x"), mSignature[i]); _tcscat(sigStringOut, stringBuffer); } ret.append(sigStringOut); return ret; }
bool CHelpDB::GetItemElement(CTSTRING& _sAlias, MSXML::IXMLDOMElementPtr& Out, bool bCreate) { bool r = false; TSTRING sXPath; MSXML::IXMLDOMNodePtr Node; TSTRING sAlias; { TCHAR* tsz = _tcsdup(_sAlias.c_str()); _tcsupr(tsz); sAlias = tsz; SAFE_FREE(tsz); } // this will look something like MSG[@ALIAS="hithere"] sprintf(sXPath, TAG_MSG _T("[@") TAG_ALIAS _T("=\"%s\"]"), sAlias.c_str()); try { Node = m_root->selectSingleNode(_bstr_t(sXPath.c_str())); if((Node == NULL) && (bCreate == true)) { MSXML::IXMLDOMElementPtr NewEl; MSXML::IXMLDOMNodePtr NewNode; NewEl = m_doc->createElement("MSG"); NewEl.QueryInterface(__uuidof(MSXML::IXMLDOMNode), &NewNode); Node = m_root->appendChild(NewNode); } if(Node != NULL) { Node.QueryInterface(__uuidof(MSXML::IXMLDOMElement), &Out); r = true; } } catch(_com_error& e) { sprintf(m_err, _T("COM Error: %08x"), e.Error()); g_pLog->msg(_T("CHelpDB::GetItemElement(%s)"), _sAlias.c_str()); } return r; }