void CCheckForUpdatesDlg::FillChangelog(CAutoConfig& versioncheck, bool official) { ProjectProperties pp; pp.lProjectLanguage = -1; if (versioncheck.GetString(_T("tortoisegit.issuesurl"), pp.sUrl)) pp.sUrl = _T("https://tortoisegit.org/issue/%BUGID%"); if (!pp.sUrl.IsEmpty()) { pp.SetCheckRe(_T("[Ii]ssues?:?(\\s*(,|and)?\\s*#?\\d+)+")); pp.SetBugIDRe(_T("(\\d+)")); } m_cLogMessage.Init(pp); CString sChangelogURL; versioncheck.GetString(_T("TortoiseGit.changelogurl"), sChangelogURL); if (sChangelogURL.IsEmpty()) sChangelogURL = _T("https://versioncheck.tortoisegit.org/changelog.txt"); else { CString tmp(sChangelogURL); sChangelogURL.FormatMessage(tmp, TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, m_updateDownloader->m_sWindowsPlatform, m_updateDownloader->m_sWindowsVersion, m_updateDownloader->m_sWindowsServicePack); } CString tempchangelogfile = CTempFiles::Instance().GetTempFilePath(true).GetWinPathString(); DWORD err; if ((err = m_updateDownloader->DownloadFile(sChangelogURL, tempchangelogfile, false)) != ERROR_SUCCESS) { CString msg = _T("Could not load changelog.\r\nError: ") + GetWinINetError(err) + _T(" (on ") + sChangelogURL + _T(")"); ::SendMessage(m_hWnd, WM_USER_FILLCHANGELOG, 0, reinterpret_cast<LPARAM>((LPCTSTR)msg)); return; } if (official) { CString signatureTempfile = CTempFiles::Instance().GetTempFilePath(true).GetWinPathString(); if ((err = m_updateDownloader->DownloadFile(sChangelogURL + SIGNATURE_FILE_ENDING, signatureTempfile, false)) != ERROR_SUCCESS || VerifyIntegrity(tempchangelogfile, signatureTempfile, m_updateDownloader)) { CString error = _T("Could not verify digital signature."); if (err) error += _T("\r\nError: ") + GetWinINetError(err) + _T(" (on ") + sChangelogURL + SIGNATURE_FILE_ENDING + _T(")"); ::SendMessage(m_hWnd, WM_USER_FILLCHANGELOG, 0, reinterpret_cast<LPARAM>((LPCTSTR)error)); DeleteUrlCacheEntry(sChangelogURL); DeleteUrlCacheEntry(sChangelogURL + SIGNATURE_FILE_ENDING); return; } } CString temp; CStdioFile file; if (file.Open(tempchangelogfile, CFile::modeRead | CFile::typeBinary)) { auto buf = std::make_unique<BYTE[]>((UINT)file.GetLength()); UINT read = file.Read(buf.get(), (UINT)file.GetLength()); bool skipBom = read >= 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF; CGit::StringAppend(&temp, buf.get() + (skipBom ? 3 : 0), CP_UTF8, read - (skipBom ? 3 : 0)); } else temp = _T("Could not open downloaded changelog file."); ::SendMessage(m_hWnd, WM_USER_FILLCHANGELOG, 0, reinterpret_cast<LPARAM>((LPCTSTR)temp)); }
ERRORCODE NodeSimCodeGenerator::GenerateMakeFile(IBMNetWorkGetService* pBmNetWork, ETYPE_BUS eBus, std::string strForCppFile) { std::string strMakeFilePath; std::string strLibFolder; std::string strSimIncludeFolder; GetBusmasterNodeSimualtionFolder(NS_MAKEFILE_FOLDER, strMakeFilePath); GetBusmasterNodeSimualtionFolder(NS_LIB_FOLDER, strLibFolder); GetBusmasterNodeSimualtionFolder(NS_INCLUDE_FOLDER, strSimIncludeFolder); CStdioFile omStdiofile; CStdioFile omStdioMakefile; CFileException omException ; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bFileOpen = FALSE; CString omStrFile = ""; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; _splitpath( strForCppFile.c_str(), drive, dir, fname, ext ); char chAbsPath[MAX_PATH] = {'\0'}; PathCombine(chAbsPath, strMakeFilePath.c_str(), "GCCDLLMakeTemplate"); strMakeFilePath = std::string(chAbsPath); bFileOpen = omStdiofile.Open(strMakeFilePath.c_str(), CFile::modeRead | CFile::typeText, &omException); if(bFileOpen!=FALSE) { CHAR* pcBuff = nullptr; CString omTemp = ""; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); //pcBuff = (char*) new char[dwSize]; pcBuff = (char*) new char[dwSize+1]; if(pcBuff!=nullptr) { memset(pcBuff, 0, dwSize); // Read the whole file and put the content to pcBuff; dwRead = omStdiofile.Read(pcBuff,dwSize); // Add end of string; *(pcBuff+dwRead) = '\0'; // copy the content to CString object; omStrFile = pcBuff; // Delete the buffer and initialise it to nullptr delete []pcBuff; pcBuff = nullptr; } //1. NS_LIB Folder omStrFile.Replace("<BUSMASTER_NS_LIB_FOLDER>", strLibFolder.c_str()); //2. Protocol Lib omStrFile.Replace("<PROTOCOL_HELPER_LIB>", GetProtocolLib(eBus).c_str()); //3. DB Object std::string strCheckSum; std::string strDbCachePath; std::string strGccVer; std::string strObjPath =""; std::string strIncPath =""; GetCurrentGccVersion(strGccVer); GetBusMasterDBCachePath(strDbCachePath); int nChannels = 0; pBmNetWork->GetChannelCount(eBus, nChannels); ICluster* pCluster = nullptr; for ( int i = 0; i < nChannels; i++ ) { int nDBCount = 0; pBmNetWork->GetDBServiceCount(eBus, i, nDBCount); for (int nDbIndex = 0; nDbIndex < nDBCount; nDbIndex++) { pBmNetWork->GetDBService(eBus, i, nDbIndex, &pCluster); strObjPath += "\""; strObjPath += strDbCachePath + "\\"; strIncPath += "-include\""; strIncPath += strDbCachePath + "\\"; if (pCluster != nullptr) { pCluster->GetDBFileChecksum(strCheckSum); strObjPath += strCheckSum + "_gcc"; strObjPath += strGccVer + ".obj"; strIncPath += strCheckSum + ".h"; } strObjPath += "\" "; strIncPath += "\" "; } } omStrFile.Replace("<DB_OBJFILES>", strObjPath.c_str()); //4. DB Include omStrFile.Replace("<DB_INCLUDES>", strIncPath.c_str()); //5. FileName omStrFile.Replace("<FILENAME>", fname); //6. BM Includes omStrFile.Replace("<BM_INCLUDES>", strSimIncludeFolder.c_str()); //7. file path char chShortPath[1024]; GetShortPathName(strForCppFile.c_str(), chShortPath, 1024); CString strTemp = chShortPath; strTemp.Replace("\\", "/"); omStrFile.Replace("<FILEPATH>", strTemp); std::strcat(fname, "make"); PathCombine(chAbsPath, drive, dir); char chFullPath[BM_MAX_PATH] = { '\0' }; PathCombine(chFullPath, chAbsPath, fname); std::string strMakeFileName = std::string(chFullPath); bFileOpen = omStdioMakefile.Open(strMakeFileName.c_str(), CFile::modeWrite | CFile::typeText | CFile::modeCreate, &omException); if(bFileOpen!=FALSE) { omStdioMakefile.WriteString(omStrFile); } } return S_OK; }
bool CStringUtils::ReadStringFromTextFile(const CString& path, CString& text) { if (!PathFileExists(path)) return false; try { CStdioFile file; // w/o typeBinary for some files \r gets dropped if (!file.Open(path, CFile::typeBinary | CFile::modeRead | CFile::shareDenyWrite)) return false; CStringA filecontent; UINT filelength = (UINT)file.GetLength(); int bytesread = (int)file.Read(filecontent.GetBuffer(filelength), filelength); filecontent.ReleaseBuffer(bytesread); text = CUnicodeUtils::GetUnicode(filecontent); file.Close(); } catch (CFileException* pE) { text.Empty(); pE->Delete(); } return true; }
BOOL CInternetConn::ReadFile(CString strUrl, CString &strFileContent) { CStdioFile* pFile = 0; strFileContent = ""; if (!m_pSharedInternetSession) return FALSE; try { m_pSharedInternetSession->SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 20000); pFile = m_pSharedInternetSession->OpenURL(strUrl, 1, INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE); if (!pFile) return FALSE; char buff[1025]; UINT len = 0; while ((len = pFile->Read(buff, 1024))) { buff[len] = 0; strFileContent += buff; } pFile->Close(); delete pFile; } catch (CInternetException* e) { e->Delete(); return FALSE; } return TRUE; }
static void skiptoeol(CStdioFile & fp) { char dummy [2]; while (fp.Read (dummy, 1)) if (dummy [0] == '\n') return; }
void CPackControl::OnButtonResult() { // TODO: Add your control notification handler code here CStdioFile f; f.Open(m_strResultName,CFile::modeRead); if(f.m_hFile!=NULL) { CTxtdlg dlg(&f); dlg.DoModal(); f.SeekToBegin(); TXTRESULT TxtResult; if(m_TxtResult.strInfo) delete[] m_TxtResult.strInfo; m_TxtResult.strInfo =new INT8[f.GetLength()]; f.Read(m_TxtResult.strInfo,f.GetLength()); m_TxtResult.nStepCode=m_pControl->nStep; m_TxtResult.nAparatusInnerSeriaNumber=0; int nSeriaNumber; m_pDatalib->GetSeriaNumber(&nSeriaNumber); m_TxtResult.nID=nSeriaNumber; m_TxtResult.nInfolth=f.GetLength(); memcpy(m_TxtResult.strName,m_pControl->strItemName,sizeof(char)*_MAX_DESCRIPTION_CNT); m_BTStart.EnableWindow(false); m_BTResult.EnableWindow(true); m_BTSave.EnableWindow(true); m_BTResultName.EnableWindow(true); m_BTInput.EnableWindow(false); }else { AfxMessageBox("控制结果文件不存在"); } f.Close(); }
CMatLoader::CMatLoader( char *name, char *path) { CStdioFile file; char filename[100]; sprintf(filename, "%s\\%s.bin", path, name); if (!file.Open(filename,CFile::modeRead | CFile::typeBinary)) { return; } int dimCount; file.Read(&dimCount, sizeof(int)); dim.resize(dimCount); file.Read(&dim.front(), sizeof(int) * dimCount); int totalSize = 1; //wcout << name.GetString() << " [ "; vector <int>::iterator iter; for (iter = dim.begin();iter != dim.end();iter++) { totalSize *= *iter; //if (iter != dim.begin()) // cout << " x "; //cout << *iter; } //cout << " ]" << endl; data = new double[totalSize]; // file.Read(&data, sizeof(double) * totalSize); file.Read(data, sizeof(double) * totalSize); double checksum = accumulate(data, data + totalSize , 0.0); file.Close(); }
void DLrtfhtml::openfile(CString filename) { CStdioFile rtf; rtf.Open(_T("F:\\\\itbook2.tit"),CStdioFile::modeRead); int len=rtf.GetLength(); rtf.SeekToBegin(); CStringA content; rtf.Read(content.GetBuffer(len),len); content.ReleaseBuffer(); rtf.Close(); char* str,*strd; str=strd=new char[len+1]; memset(str,'\0',sizeof(str)); int bg,end; bg=end=0; char* p; while((end=content.Find("\\\'",end))>=0) { if(end==0 || content.GetAt(end-1)!='\\') {//转汉字 CStringA s; if(end!=bg) { strcpy(str,(LPSTR)(LPCSTR)content.Mid(bg,end-bg)); str+=(end-bg); } *str=strtol(content.Mid(end+2,2),&p,16); str++; bg=end+4; } else {// \\' 去斜杆 if(end!=bg) { strcpy(str,(LPSTR)(LPCSTR)content.Mid(bg,end-bg-1)); // '之前还有两个" \ " str+=(end-bg-1); } strcpy(str,(LPSTR)(LPCSTR)content.Mid(end,2)); str+=2; bg=end+2; } end++; } int leng=content.GetLength(); if((content.GetLength()-bg)>2)//如果再最后两个字符找到\'则会=2 当然根据rtf文档绝对不会这样。 strcpy(str,(LPSTR)(LPCSTR)content.Mid(bg)); //} int unicodeLen = ::MultiByteToWideChar( CP_ACP,0,strd,-1,NULL,0); MultiByteToWideChar(CP_ACP,0,strd,-1,(LPWSTR)destcon.GetBuffer(unicodeLen),unicodeLen); destcon.ReleaseBuffer(); }
CheckVersion::CheckStatus CAboutDlg::CheckLatestVersion(std::wstring &latest) { CInternetSession session(L"PasswordSafe Version Check"); CStdioFile *fh; // Put up hourglass...this might take a while CWaitCursor waitCursor; try { // Loading the file as binary since we're treating it as UTF-8 fh = session.OpenURL(L"https://pwsafe.org/latest.xml", 1, (INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD)); } catch (CInternetException *) { // throw; return CheckVersion::CANT_CONNECT; } ASSERT(fh != NULL); CString latest_xml; unsigned char buff[BUFSIZ + 1]; StringX chunk; UINT nRead; CUTF8Conv conv; while ((nRead = fh->Read(buff, BUFSIZ)) != 0) { buff[nRead] = '\0'; // change to widechar representation if (!conv.FromUTF8(buff, nRead, chunk)) { fh->Close(); delete fh; session.Close(); return CheckVersion::CANT_READ; } else latest_xml += chunk.c_str(); } fh->Close(); delete fh; session.Close(); waitCursor.Restore(); // restore normal cursor CheckVersion vh(m_nMajor, m_nMinor, m_nBuild); return vh.CheckLatestVersion(LPCWSTR(latest_xml), latest); }
CString CKDApp::GetUpdateAppOnLineVer(LPCTSTR lpQueryUrl, LPCTSTR lpQueryKeyword, const LONGLONG i64QueryOffset, const short unsigned int iQueryVerSize) { CString sRes; CInternetSession session(_T("Check Update App Session")); CStdioFile *pFile = NULL; TRY { pFile = session.OpenURL(lpQueryUrl); } CATCH_ALL(e) { } END_CATCH_ALL if (pFile) { CString sPageContext; CString sBuf; char *pBuf = new char[UPDATE_QUERY_SIZE]; while (pFile->Read(pBuf, UPDATE_QUERY_SIZE)) { sBuf = pBuf; sPageContext.Append(sBuf); } int iPos = sPageContext.Find(lpQueryKeyword); if (-1 != iPos) { LPCTSTR lpPageContext = sPageContext; lpPageContext += iPos + i64QueryOffset; LPTSTR lpVersion = new TCHAR[iQueryVerSize + 1]; _tcsncpy(lpVersion, lpPageContext, iQueryVerSize); *(lpVersion + iQueryVerSize) = _T('\0'); sRes = lpVersion; delete [] lpVersion; } delete pBuf; pFile->Close(); delete pFile; } session.Close(); return sRes; }
void CFileClipboardDlg::ReadFileClipboard(CString szFilename) { CStdioFile fInput; UINT nFileSize; char *szFileData; char *pEnd, *pStart; if (fInput.Open(szFilename, CFile::typeText|CFile::modeRead) == TRUE) { nFileSize = (UINT)fInput.GetLength(); szFileData = (char*)malloc(nFileSize + 1); if (szFileData) { nFileSize = fInput.Read(szFileData, nFileSize); if (nFileSize > 0) { szFileData[nFileSize] = 0; pStart = szFileData; do { pEnd = strchr(pStart, '\n'); if (pEnd) { *pEnd = 0; pEnd++; } if (strlen(pStart) > 0) { m_cFileClipboardList.InsertItem(m_cFileClipboardList.GetItemCount() - 1, pStart); } pStart = pEnd; } while (pStart); } free(szFileData); } fInput.Close(); } }
int C51JobWebPost::GetGateWayIP(CString &strIP) { CInternetSession session; CString strTemp = ""; char temp[1001] = {0}; CStdioFile *pFile = session.OpenURL("http://www.ip138.com/ip2city.asp"); if (pFile != NULL) { long len = pFile->GetLength(); if (len > 1000) { len = 1000; } pFile->SeekToBegin(); pFile->Read(temp,len); temp[len] = '\0'; strTemp.Format("%s",temp); strTemp.MakeLower(); if (strTemp.Find("您的ip地址是:[") !=-1) { CString strBefore = "您的ip地址是:["; CString strAfter = "]"; strIP = GetKeyString(strTemp,strBefore,strAfter); pFile->Close(); delete pFile; pFile = NULL; return 0; } if (pFile == NULL) { pFile->Close(); delete pFile; pFile = NULL; } } return -1; }
void OnCfg2Bin(CString strSrcFile, CString strDstFile, BOOL bForce) { CFile out; CStdioFile in; CString strRead; char * p; BOOL bSettings = TRUE; int iItem; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } #ifndef __GNUC__ AfxGetApp()->BeginWaitCursor(); #endif p = (char *)malloc(SETTINGS_FILE_SIZE); memset(p, 0, SETTINGS_FILE_SIZE); iItem = 0; #ifndef __GNUC__ while (in.ReadString(strRead)) { #else while (!in.eof()) { std::getline(in, strRead); strRead.TrimRight(); #endif if (!strRead.GetLength()) { continue; } if (strRead.GetAt(0) == '[') { strRead.MakeLower(); if (strRead.Left(10) == "[settings]") { bSettings = TRUE; } else if (strRead.Left(10) == "[digitmap]") { bSettings = FALSE; } continue; } else if (strRead.Left(12) == "ENDOFCONFIG=") { break; } else { if (bSettings) { AR168CompareCfg((char *)p, strRead); } else { if (iItem < DIGITMAP_ENTRY_NUM) { if (AR168CompareMap((char *)(p + OPT_DIGIT_MAP), strRead, iItem)) { iItem++; } } } } } out.Write(p, SETTINGS_FILE_SIZE); #ifndef __GNUC__ AfxGetApp()->EndWaitCursor(); #endif free(p); in.Close(); out.Close(); } void OnBin2H(CString strSrcFile, CString strDstFile, BOOL bForce, int iAddressOffset, int iConvertLength) { CFile in; CStdioFile out; CString strAnswer, strName; CString strOut, strItem; TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; char * p; int iLength, i, j; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } iLength = (int)in.GetLength(); p = (char *)malloc(iLength); in.Read(p, iLength); if (iConvertLength == 0) { iConvertLength = iLength; } #ifndef __GNUC__ _wsplitpath(strDstFile, drive, dir, fname, ext); #else strcpy(fname,basename(strDstFile)); #endif strName = fname; strName.MakeUpper(); #ifndef __GNUC__ strOut.Format(_T("#define DATA_%s_SIZE\t\t%d\n"), strName, iConvertLength); #else { char buff[511]; sprintf(buff, _T("#define DATA_%s_SIZE\t\t%d\n"), strName.c_str(), iConvertLength); strOut = buff; } #endif out.WriteString(strOut); #ifndef __GNUC__ strOut.Format(_T("const unsigned char _c_%s[DATA_%s_SIZE] = {\n"), fname, strName); #else { char buff[511]; sprintf(buff, _T("const unsigned char _c_%s[DATA_%s_SIZE] = {\n"), fname, strName.c_str()); strOut = buff; } #endif out.WriteString(strOut); for (i = iAddressOffset; i < iAddressOffset+iConvertLength; i += FRAME_LEN) { strOut = _T(""); for (j = 0; j < FRAME_LEN; j ++) { if (i+j < iAddressOffset+iConvertLength) { #ifndef __GNUC__ strItem.Format(_T("0x%02x"), (unsigned char)p[i+j]); #else { char buff[511]; sprintf(buff, _T("0x%02x"), (unsigned char)p[i+j]); strItem = buff; } #endif strOut += strItem; } if (i+j < ((iAddressOffset+iConvertLength) - 1)) { strOut += _T(", "); } } strOut += _T("\n"); out.WriteString(strOut); } #ifndef __GNUC__ strOut.Format(_T("};\n")); #else { char buff[511]; sprintf(buff, _T("};\n")); strOut = buff; } #endif out.WriteString(strOut); free(p); in.Close(); out.Close(); }
// AppName Version Url bool CKDApp::GetUpdateAppOnLineVer(LPCTSTR lpQueryUrl, const CStringArray &saQueryAppName, const CArray<int, int> &aiQueryVerSize, CStringArray &saReturnVer, CStringArray &saReturnUrl) { saReturnVer.RemoveAll(); saReturnUrl.RemoveAll(); int i, iCount = saQueryAppName.GetCount(); if ((iCount < 1) || (iCount != aiQueryVerSize.GetCount())) return false; saReturnVer.SetSize(iCount); saReturnUrl.SetSize(iCount); bool bRes = true; CInternetSession session(_T("Check Update App Session")); CStdioFile *pFile = NULL; TRY { pFile = session.OpenURL(lpQueryUrl); } CATCH_ALL(e) { } END_CATCH_ALL if (pFile) { CString sPageContext; CString sBuf; char *pBuf = new char[UPDATE_QUERY_SIZE]; while (pFile->Read(pBuf, UPDATE_QUERY_SIZE)) { sBuf = pBuf; sPageContext.Append(sBuf); } int iPos; iPos = sPageContext.Find(_T("404 Not Found")); if (-1 != iPos) { bRes = false; iCount = 0; } for (i=0 ; i<iCount ; i++) { if (saQueryAppName[i].IsEmpty()) continue; iPos = sPageContext.Find(saQueryAppName[i]); if (-1 != iPos) { LPCTSTR lpPageContext = sPageContext; lpPageContext += iPos + _tcslen(saQueryAppName[i]) + 1; CString *psReturnVer = (CString *)&saReturnVer.GetAt(i); LPTSTR lpVersion = psReturnVer->GetBuffer(aiQueryVerSize[i] + 1); _tcsncpy(lpVersion, lpPageContext, aiQueryVerSize[i]); *(lpVersion + aiQueryVerSize[i]) = _T('\0'); psReturnVer->ReleaseBuffer(); int iTextWrite = 0; psReturnVer = (CString *)&saReturnUrl.GetAt(i); lpVersion = psReturnVer->GetBuffer(MAX_PATH); lpPageContext += aiQueryVerSize[i] + 1; while ((*lpPageContext != _T('\0')) && (*lpPageContext != _T('\n')) && (iTextWrite < MAX_PATH)) { *lpVersion = *lpPageContext; lpVersion++; lpPageContext++; iTextWrite++; } *lpVersion = _T('\0'); psReturnVer->ReleaseBuffer(); } } delete pBuf; pFile->Close(); delete pFile; } else { bRes = false; } session.Close(); return bRes; }
BOOL CBuildProgram::bCreateMakeFile(CString& omStrMakeFileTemplateName, CString& omStrMakeFileName ) { CStdioFile omStdiofile; CFileException omException ; CString omStrFile = ""; BOOL bReturn = FALSE; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bFileOpen = FALSE; CString omStrErrorMessage = ""; char acErrorMsg[defSIZE_OF_ERROR_BUFFER]; // Open the make file template. TRY { bFileOpen = omStdiofile.Open(omStrMakeFileTemplateName, CFile::modeRead | CFile::typeText, &omException); if(bFileOpen!=FALSE) { CHAR* pcBuff = NULL; CString omTemp = ""; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); pcBuff = (char*) new char[dwSize]; if(pcBuff!=NULL) { memset(pcBuff, 0, dwSize); // Read the whole file and put the content to pcBuff; dwRead = omStdiofile.Read(pcBuff,dwSize); // Add end of string; *(pcBuff+dwRead) = '\0'; // copy the content to CString object; omStrFile = pcBuff; // Delete the buffer and initialise it to NULL delete []pcBuff; pcBuff = NULL; char acStrShortPath[1000] ; // Convert long name to short name for GCC compiler dwConvertShortPathName(omStrMakeFileTemplateName,acStrShortPath); omTemp = acStrShortPath; INT nIndex = 0; // Get the path of make file temptate in temp object nIndex = omStrMakeFileTemplateName.ReverseFind('\\'); if(nIndex>=0) { omTemp = omStrMakeFileTemplateName.Left(nIndex); // Replace all occurrence of "<INSTALLDIR>" string with template path omStrFile.Replace("<INSTALLDIR>",omTemp); } // Replace all occurence of <SRCDIR> and <FILENAME> with source // directory and file name respectively. nIndex = omTemp.ReverseFind('\\'); if(nIndex>=0) { nIndex = m_omStrSourceFilename.ReverseFind('.'); if(nIndex>=0) { omTemp = m_omStrSourceFilename.Left(nIndex); // Replace all occurrence of "<INSTALLDIR>" string with template path omStrFile.Replace("<INPUTFILE>",omTemp); } omTemp = m_omStrSourceFilename; omTemp.Replace('\\', '/'); omTemp.Replace(" ", "\\ "); omStrFile.Replace("<CPPFILE>", omTemp); bReturn = TRUE; } } omStdiofile.Close(); } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // make file template open error notification // AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); m_omStrArray.Add(acErrorMsg); bAddString(m_omStrArray); } if(bReturn == TRUE) { bFileOpen = omStdiofile.Open( omStrMakeFileName, CFile::modeCreate | CFile::modeWrite, &omException); if(bFileOpen!=FALSE) { //AfxMessageBox(omStrFile); omStdiofile.WriteString(omStrFile); omStdiofile.Close(); } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); //AfxMessageBox(acErrorMsg , // MB_ICONERROR| MB_SYSTEMMODAL|MB_OK, // 0); m_omStrArray.Add(acErrorMsg); bAddString(m_omStrArray); bReturn = FALSE; } } } CATCH_ALL(pomE) { if(pomE != NULL ) { // Get the exception error message pomE->GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); omStrErrorMessage = acErrorMsg; //Display the error //AfxMessageBox(omStrErrorMessage , // MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,0); m_omStrArray.Add(acErrorMsg); bAddString(m_omStrArray); pomE->Delete(); } bReturn = FALSE; } END_CATCH_ALL return bReturn; }
inline UINT DownLoad(LPVOID pParam) { while (1) { if(TempFileList.size()>0) { m_HeadCS.Lock(); std::vector<std::string>::reverse_iterator rit = TempFileList.rbegin(); LPCTSTR pszFace = (LPCTSTR)((std::string)*rit).c_str();; TempFileList.erase((++rit).base()); m_HeadCS.Unlock(); CString DATFile=TEXT("FaceImage.DAT"); CFileFind finder; BOOL FF; FF=finder.FindFile(DATFile); if(!FF){ CFile pwFile; pwFile.Open(DATFile,CFile::modeCreate); pwFile.Close(); } CFile pwFile; pwFile.Open(DATFile,CFile::modeReadWrite| CFile::typeBinary); char FileNum[10]; pwFile.Read(FileNum,9); sprintf(FileNum,"%d",atol(FileNum)+1); pwFile.SeekToBegin(); pwFile.Write(FileNum,9); CInternetSession is; CStdioFile *psf; CString picUrl="http://www.17tzy.com/tzyBBS/avatars/common/0.bmp"; psf = is.OpenURL( picUrl, 1, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD); BITMAPFILEHEADER bmfh; // 步骤1 读取文件头 int nCount = psf->Read((LPVOID) &bmfh, sizeof(BITMAPFILEHEADER)); // 判断是否是BMP格式的位图 if(bmfh.bfType != BMP_HEADER_MARKER) { continue; } // 计算信息头加上调色板的大小并分内存 int nSize = bmfh.bfOffBits - sizeof(BITMAPFILEHEADER); LPBITMAPINFOHEADER m_pBMIH = (LPBITMAPINFOHEADER) new BYTE[nSize]; // 步骤2 读取信息头和调色板 nCount = psf->Read(m_pBMIH, nSize); // 步骤3 读取图象数据 LPBYTE m_pBits = (LPBYTE) new BYTE[m_pBMIH->biSizeImage]; nCount = psf->Read(m_pBits, m_pBMIH->biSizeImage); //写入到DAT pwFile.SeekToEnd(); pwFile.Write(pszFace,128); // 进行写操作 pwFile.Write((LPVOID) &bmfh, sizeof(BITMAPFILEHEADER)); pwFile.Write((LPVOID) m_pBMIH, nSize); pwFile.Write((LPVOID) m_pBits, m_pBMIH->biSizeImage); m_HeadCS.Lock(); ImgFileList.push_back(pszFace); m_HeadCS.Unlock(); } Sleep(1); } return 0; }
/***************************************************************************** Function Name : COM_bSetCheckSum Input(s) : omStrConfigFileName : reference to File name pucCheckSum : Returns computed check sum Output : BOOL Functionality : This method computes the checksum for a given bytes in a file. The file is opened and checksum is computed for all bytes except the last byte. Returns TRUE for sucess and FALSE for failure. The same checksum is overwritten at the last byte in file. For COM Support Member of : CComputeCheckSum Friend of : - Author : Anish kr Creation Date : 6/05/10 Modifications : ******************************************************************************/ BOOL CComputeCheckSum::COM_bSetCheckSum(CString &omStrConfigFileName, UCHAR* pucCheckSum, CString &strError) { CStdioFile omStdiofile; CFileException omException; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bReturn = FALSE; BOOL bFileOpen = FALSE; CString omStrStrErrorMessage = _T(""); TCHAR acErrorMsg[defSIZE_OF_ERROR_BUFFER]; // Open the configration file template. TRY { bFileOpen = omStdiofile.Open(omStrConfigFileName, CFile::modeReadWrite| CFile::typeBinary, &omException); if(bFileOpen!=FALSE) { UCHAR *pucBuff = NULL; UCHAR ucCheckSum = 0; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); pucBuff = static_cast<UCHAR*> (new UCHAR[dwSize]); if(pucBuff!=NULL) { // Read the whole file and put the content to pucBuff; dwRead = omStdiofile.Read(pucBuff,dwSize); // compute the checksum bReturn = bComputeCheckSum(pucBuff,dwSize, &ucCheckSum); if(bReturn == TRUE) { // Seek to the last byte to store checksum omStdiofile.Seek(dwSize,CFile::begin); // Write one byte checksum omStdiofile.Write(&ucCheckSum,1); // return the checksum if(pucCheckSum!= NULL ) { *pucCheckSum = ucCheckSum; } else { bReturn = FALSE; } } delete [] pucBuff; pucBuff = NULL; } omStdiofile.Close(); } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // configuration file open error notification } } CATCH_ALL(pomE) { if(pomE != NULL ) { // Get the exception error message pomE->GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); } } END_CATCH_ALL strError = acErrorMsg; return bReturn; }
BOOL CComputeCheckSum::bGetCheckSum(CString &omStrConfigFileName, UCHAR* pucCheckSum, UCHAR* pucCheckSumInFile) { CStdioFile omStdiofile; CFileException omException ; DWORD dwSize = 0; DWORD dwRead = 0; BOOL bReturn = FALSE; BOOL bFileOpen = FALSE; CString omStrErrorMessage = _T(""); TCHAR acErrorMsg[defSIZE_OF_ERROR_BUFFER]; // Open the configration file. TRY { bFileOpen = omStdiofile.Open(omStrConfigFileName, CFile::modeRead | CFile::typeBinary, &omException); if(bFileOpen!=FALSE) { UCHAR *pucBuff = NULL; // Get the size of file dwSize = (DWORD)omStdiofile.GetLength(); if( dwSize > 0) { pucBuff = static_cast<UCHAR*> (new UCHAR[dwSize]); if(pucBuff!=NULL) { // Read the whole file and put the content to pucBuff; dwRead = omStdiofile.Read(pucBuff,dwSize); // Compute the checksum bReturn = bComputeCheckSum(pucBuff,dwSize - 1, pucCheckSum); // Get the check sum stored in file ( Last byte ) *pucCheckSumInFile = pucBuff[dwSize-1]; delete [] pucBuff; pucBuff = NULL; } } omStdiofile.Close(); bReturn = TRUE; } else { // Get the exception error message omException.GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); // configuration file open error notification //AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,nZERO); MessageBox(NULL,acErrorMsg, defPROJECT_NAME,MB_OK|MB_ICONERROR|MB_TOPMOST); } } CATCH_ALL(pomE) { if(pomE != NULL ) { // Get the exception error message pomE->GetErrorMessage(acErrorMsg,sizeof(acErrorMsg)); //Display the error //AfxMessageBox(acErrorMsg ,MB_ICONERROR| MB_SYSTEMMODAL|MB_OK,nZERO); MessageBox(NULL,acErrorMsg, defPROJECT_NAME,MB_OK|MB_ICONERROR|MB_TOPMOST); } } END_CATCH_ALL return bReturn; }
CDibSection* InformApp::GetImage(const char* path) { // Check if it's a PNG file CStdioFile imageFile; if (!imageFile.Open(path,CFile::modeRead|CFile::typeBinary)) return 0; png_byte fileHeader[8]; imageFile.Read(fileHeader,8); bool isPNG = (png_sig_cmp(fileHeader,0,8) == 0); if (isPNG) { // Prepare to read the PNG file png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,(png_voidp)NULL,NULL,NULL); if (png_ptr == NULL) return 0; png_infop info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_read_struct(&png_ptr,(png_infopp)NULL,(png_infopp)NULL); return 0; } png_infop end_info = png_create_info_struct(png_ptr); if (end_info == NULL) { png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)NULL); return 0; } // Set up the point to return to in case of error png_bytep* rowPointers = NULL; if (setjmp(png_jmpbuf(png_ptr))) { if (rowPointers) delete[] rowPointers; png_destroy_read_struct(&png_ptr,&info_ptr,&end_info); return 0; } png_init_io(png_ptr,imageFile.m_pStream); png_set_sig_bytes(png_ptr,8); png_read_info(png_ptr,info_ptr); // Get details of the image png_uint_32 width = png_get_image_width(png_ptr,info_ptr); png_uint_32 height = png_get_image_height(png_ptr,info_ptr); int bit_depth = png_get_bit_depth(png_ptr,info_ptr); int color_type = png_get_color_type(png_ptr,info_ptr); // Set up transforms to the required format if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8) png_set_palette_to_rgb(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png_ptr); if (png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); double gamma; if (png_get_gAMA(png_ptr,info_ptr,&gamma)) png_set_gamma(png_ptr,2.2,gamma); if (bit_depth == 16) png_set_strip_16(png_ptr); if (bit_depth < 8) png_set_packing(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); png_set_bgr(png_ptr); png_set_filler(png_ptr,0xFF,PNG_FILLER_AFTER); // Create a bitmap HDC dc = ::GetDC(NULL); CDibSection* dib = new CDibSection(); BOOL created = dib->CreateBitmap(dc,width,height); ::ReleaseDC(NULL,dc); if (!created) { png_destroy_read_struct(&png_ptr,&info_ptr,&end_info); return NULL; } // Read in the image rowPointers = new png_bytep[height]; for (int i = 0; i < (int)height; i++) rowPointers[i] = ((png_bytep)dib->GetBits())+(width*i*4); png_read_image(png_ptr,rowPointers); png_read_end(png_ptr,end_info); delete[] rowPointers; png_destroy_read_struct(&png_ptr,&info_ptr,&end_info); return dib; } else { imageFile.SeekToBegin(); struct jpeg_decompress_struct info; struct JPEGErrorInfo error; // Initialize the error handling info.err = jpeg_std_error(&(error.base)); error.base.error_exit = errorJPEGExit; error.base.output_message = outputJPEGMessage; if (setjmp(error.errorJump)) { jpeg_destroy_decompress(&info); return NULL; } // Set up the decompression jpeg_create_decompress(&info); jpeg_stdio_src(&info,imageFile.m_pStream); // Read the image attributes jpeg_read_header(&info,TRUE); jpeg_calc_output_dimensions(&info); int width = info.output_width; int height = info.output_height; // Force RGB output info.out_color_space = JCS_RGB; // Create a bitmap HDC dc = ::GetDC(NULL); CDibSection* dib = new CDibSection(); BOOL created = dib->CreateBitmap(dc,width,height); ::ReleaseDC(NULL,dc); if (!created) { jpeg_destroy_decompress(&info); return NULL; } // Get an output buffer JSAMPARRAY buffer = (*info.mem->alloc_sarray) ((j_common_ptr)&info,JPOOL_IMAGE,width*3,1); // Read in the image jpeg_start_decompress(&info); while ((int)info.output_scanline < height) { jpeg_read_scanlines(&info,buffer,1); BYTE* pixelRow = ((BYTE*)dib->GetBits())+(width*(info.output_scanline-1)*4); for (int i = 0; i < width; i++) { pixelRow[(i*4)+0] = (*buffer)[(i*3)+2]; pixelRow[(i*4)+1] = (*buffer)[(i*3)+1]; pixelRow[(i*4)+2] = (*buffer)[(i*3)+0]; pixelRow[(i*4)+3] = 0xFF; } } jpeg_finish_decompress(&info); jpeg_destroy_decompress(&info); return dib; } }
CSize InformApp::GetImageSize(const char* path) { CSize size(0,0); // Check if it's a PNG file CStdioFile imageFile; if (!imageFile.Open(path,CFile::modeRead|CFile::typeBinary)) return size; png_byte fileHeader[8]; imageFile.Read(fileHeader,8); bool isPNG = (png_sig_cmp(fileHeader,0,8) == 0); if (isPNG) { png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,(png_voidp)NULL,NULL,NULL); if (png_ptr == NULL) return size; png_infop info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_read_struct(&png_ptr,(png_infopp)NULL,(png_infopp)NULL); return size; } png_infop end_info = png_create_info_struct(png_ptr); if (end_info == NULL) { png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)NULL); return size; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr,&info_ptr,&end_info); return size; } png_init_io(png_ptr,imageFile.m_pStream); png_set_sig_bytes(png_ptr,8); png_read_info(png_ptr,info_ptr); size.cx = png_get_image_width(png_ptr,info_ptr); size.cy = png_get_image_height(png_ptr,info_ptr); png_destroy_read_struct(&png_ptr,&info_ptr,&end_info); return size; } else { imageFile.SeekToBegin(); struct jpeg_decompress_struct info; struct JPEGErrorInfo error; info.err = jpeg_std_error(&(error.base)); error.base.error_exit = errorJPEGExit; error.base.output_message = outputJPEGMessage; if (setjmp(error.errorJump)) { jpeg_destroy_decompress(&info); return size; } jpeg_create_decompress(&info); jpeg_stdio_src(&info,imageFile.m_pStream); jpeg_read_header(&info,TRUE); jpeg_calc_output_dimensions(&info); size.cx = info.output_width; size.cy = info.output_height; jpeg_destroy_decompress(&info); return size; } }
/**************************************************************************** readmagic Reads a four-character magic string from a stream. ****************************************************************************/ static void readmagic(CStdioFile & file, char * magic) { file.Read (magic, 4); magic[4] = 0; }
void OnPB2Bin(CString strSrcFile, CString strDstFile, BOOL bForce) { CFile out; CStdioFile in; CString strRead; char * p; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } #ifndef __GNUC__ AfxGetApp()->BeginWaitCursor(); #endif p = (char *)malloc(PHONEBOOK_FILE_SIZE); memset(p, 0, PHONEBOOK_FILE_SIZE); #ifndef __GNUC__ while (in.ReadString(strRead)) { #else while (!in.eof()) { std::getline(in, strRead); strRead.TrimRight(); #endif if (!strRead.GetLength()) { continue; } if (strRead.Left(11) == "[phonebook]") { continue; } AR168ComparePB((char *)p, strRead); } out.Write(p, PHONEBOOK_FILE_SIZE); #ifndef __GNUC__ AfxGetApp()->EndWaitCursor(); #endif free(p); in.Close(); out.Close(); } void OnBin2PB(CString strSrcFile, CString strDstFile, BOOL bForce) { CStdioFile in, out; CString cStr; char * p; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite|CFile::typeText)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } #ifndef __GNUC__ AfxGetApp()->BeginWaitCursor(); #endif p = (char *)malloc(PHONEBOOK_FILE_SIZE); in.Read(p, PHONEBOOK_FILE_SIZE); AR168ConvertPB((char *)p, cStr); out.WriteString(cStr); #ifndef __GNUC__ AfxGetApp()->EndWaitCursor(); #endif free(p); in.Close(); out.Close(); }