void CMyDrawPictureClass::drawPicture() { this->UpdateData(); CString offsetColorStr=_T("0"); DWORD lowColor=0; this->GetDlgItem(IDC_EDIT_OffsetColor1)->GetWindowTextW(offsetColorStr); lowColor = ::wcstol(offsetColorStr,0,16); BYTE offr,offg,offb; offr = GetRValue(lowColor); offg = GetGValue(lowColor); offb = GetBValue(lowColor); CRect rctWindowSize,rctTargetPic; m_LoadSourcePic.GetWindowRect(rctWindowSize); this->GetDlgItem(IDC_STATIC_TARGET)->GetWindowRect(&rctTargetPic); //CClientDC cDC(this); HDC hScrDC,hMemDC; ////为屏幕创建设备描述表 hScrDC = CreateDC(_T("DISPLAY"), NULL, NULL, NULL); //为屏幕设备描述表创建兼容的内存设备描述表 hMemDC = CreateCompatibleDC(hScrDC); //////////////////创建一个原图大小的位图////////////////////// HBITMAP hBitmap = ::CreateCompatibleBitmap(hScrDC,m_Width,this->m_Height); HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC,hBitmap); BitBlt(hMemDC, 0, 0, m_Width,m_Height,hScrDC, rctWindowSize.left, rctWindowSize.top, CAPTUREBLT|SRCCOPY); hBitmap = (HBITMAP)SelectObject(hMemDC,hOldBitmap); // 24位图的BITMAPINFO BITMAPINFO *pBITMAPINFO = (BITMAPINFO*)malloc(sizeof(BITMAPINFOHEADER)); memset(pBITMAPINFO, 0, sizeof(BITMAPINFOHEADER)); BITMAPINFOHEADER *pInfo_Header = (BITMAPINFOHEADER *)pBITMAPINFO; pInfo_Header->biSize = sizeof(BITMAPINFOHEADER); pInfo_Header->biWidth = m_Width; pInfo_Header->biHeight = m_Height; pInfo_Header->biPlanes = 1; pInfo_Header->biBitCount = 24; pInfo_Header->biCompression = BI_RGB; // 获得数据buf DWORD bufSize = (pInfo_Header->biWidth * 3 + 3) / 4 * 4 * pInfo_Header->biHeight; BYTE * pBuffer = new BYTE[bufSize]; int aHeight=pInfo_Header->biHeight; if(::GetDIBits(hMemDC, hBitmap, 0, aHeight, pBuffer,pBITMAPINFO, DIB_RGB_COLORS) == 0) { return ; } BYTE fr,fg,fb,lr,lg,lb; fr = GetRValue(m_ForegroundColor); fg = GetGValue(m_ForegroundColor); fb = GetBValue(m_ForegroundColor); lr = GetRValue(m_LowColor); lg = GetGValue(m_LowColor); lb = GetBValue(m_LowColor); int pitch=m_Width%4; for(int i=0;i<m_Height;i++) { int realPitch=i*pitch; for(int j=0;j<m_Width;j++) { UCHAR b=pBuffer[(i*m_Width+j)*3+realPitch]; UCHAR g=pBuffer[(i*m_Width+j)*3+1+realPitch]; UCHAR r=pBuffer[(i*m_Width+j)*3+2+realPitch]; //helpcolor=RGB(r,g,b); if(abs(r-fr)<=offr&&abs(g-fg)<=offg&&abs(b-fb)<=offb) { continue; } else { pBuffer[(i*m_Width+j)*3+realPitch] = lb; pBuffer[(i*m_Width+j)*3+1+realPitch] = lg; pBuffer[(i*m_Width+j)*3+2+realPitch] = lr; } } } //保存到文件并创建位图结构 BITMAPFILEHEADER bmfh; ZeroMemory(&bmfh,sizeof(BITMAPFILEHEADER)); *((char*)&bmfh.bfType) = 'B'; *(((char*)&bmfh.bfType) + 1) = 'M'; bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); bmfh.bfSize = bmfh.bfOffBits + (m_Width * m_Height) * pInfo_Header->biBitCount / 8; CFile file; if(file.Open(g_CurrentExePath+_T("TCTEMP.bmp"),CFile::modeWrite|CFile::modeCreate)) { file.Write(&bmfh,sizeof(BITMAPFILEHEADER)); file.Write(&(pBITMAPINFO->bmiHeader),sizeof(BITMAPINFOHEADER)); file.Write(pBuffer,bufSize); file.Close(); } //HBITMAP hBitmapTTT = (HBITMAP)LoadImage( AfxGetInstanceHandle(),_T("TCTEMP.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); HBITMAP hBitmapTTT = (HBITMAP)LoadImage( NULL,g_CurrentExePath+_T("TCTEMP.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); if(hBitmapTTT==NULL) { //::AfxMessageBox(_T("加载位图资源失败!")); return ; } m_TargetPic.SetBitmap(hBitmapTTT); //helpBMP =(HBITMAP)SelectObject(hMemDC,m_Hbitmap); //helpBMP =(HBITMAP)SelectObject(cDC.GetSafeHdc(),m_Hbitmap); //CRect rt; //m_LoadSourcePic.GetClientRect(&rt); //m_SourcePic.GetClientRect(&rt); //int width = rt.right-rt.left; //int height = rt.bottom-rt.top; //StretchBlt(cDC.GetSafeHdc(),rt.left+8,rt.top+8,width,height,hMemDC,0,0,width,height,SRCCOPY); //::BitBlt(cDC.GetSafeHdc(),rt.left+8,rt.top+8,width,height,hMemDC,0,0,SRCCOPY); //::StretchBlt(hMemDC,rt.left+8,rt.top+8,width,height,cDC.GetSafeHdc(),0,0,width,height,SRCCOPY); //SelectObject(hMemDC,helpBMP); //m_SourcePic.SetBitmap(helpBMP); delete [] pBuffer; ::DeleteDC(hMemDC); ::DeleteDC(hScrDC); TCHAR currentPath[MAX_PATH]={0}; ::GetCurrentDirectoryW(MAX_PATH,currentPath); m_SavePicPath.Format(_T("%s\\TCTEMP.bmp"),g_CurrentExePath); return ; }
BOOL CModbusM::LoadFromFile(CString strFile) { CFile f; CString strBuf,str; try { if(!f.Open(strFile,CFile::modeRead)) return FALSE; CHAR buffer[4096]; DWORD dwRead=0; // Read in 4096-byte blocks, // remember how many bytes were actually read, // and try to write that many out. This loop ends // when there are no more bytes to read. do { dwRead = f.Read(buffer, 4096); if(dwRead > 0) { int nLen = strBuf.GetLength(); strBuf+=buffer; strBuf.Truncate(nLen+dwRead); } } while (dwRead > 0); f.Close(); //AfxMessageBox(strBuf); strBuf.MakeUpper(); strBuf.Remove(';'); int nIndex = 0; int nProcIndex = -1; do { nIndex = strBuf.Find("\n"); str = strBuf.Left(nIndex+1); if(str.Find("PORT") != -1) { str.TrimLeft("PORT"); str.Trim();str.Trim("="); PORT = atoi(str); } if(str.Find("BAUDRATE") != -1) { str.TrimLeft("BAUDRATE"); str.Trim();str.Trim("="); BAUDRATE = atoi(str); } if(str.Find("STOPBITS") != -1) { str.TrimLeft("STOPBITS"); str.Trim();str.Trim("="); STOPBITS = atoi(str); } if(str.Find("PARITY") != -1) { str.TrimLeft("PARITY"); str.Trim();str.Trim("="); PARITY = atoi(str); } if(str.Find("BYTETIME") != -1) { str.TrimLeft("BYTETIME"); str.Trim();str.Trim("="); BYTETIME = atoi(str); } if(str.Find("WAITRESP") != -1) { str.TrimLeft("WAITRESP"); str.Trim();str.Trim("="); WAITRESP = atoi(str); } if(str.Find("NEXTMESSAGE") != -1) { str.TrimLeft("NEXTMESSAGE"); str.Trim();str.Trim("="); NEXTMESSAGE = atoi(str); } if(str.Find("AMOUNTBYTE") != -1) { str.TrimLeft("AMOUNTBYTE"); str.Trim();str.Trim("="); AMOUNTBYTE = atoi(str); } if(str.Find("CONTROLPOTOK") != -1) { str.TrimLeft("CONTROLPOTOK"); str.Trim();str.Trim("="); CONTROLPOTOK = atoi(str); } if(str.Find("NUMBER_NO_ANSWER") != -1) { str.TrimLeft("NUMBER_NO_ANSWER"); str.Trim();str.Trim("="); NUMBER_NO_ANSWER = atoi(str); } if(str.Find("MODBUS_TYPE") != -1) { str.TrimLeft("MODBUS_TYPE"); str.Trim();str.Trim("="); MODBUS_TYPE = atoi(str); } if(str.Find("NUMBER_OF_PRIBOR") != -1) { str.TrimLeft("NUMBER_OF_PRIBOR"); str.Trim();str.Trim("="); m_ModbusPriborArray.SetSize(atoi(str)); } if(str.Find("MAKE_PRIBOR") != -1) { str.TrimLeft("MAKE_PRIBOR"); str.Trim();str.Trim("="); if((atoi(str) > 0)&&(atoi(str) <= m_ModbusPriborArray.GetSize())) nProcIndex = atoi(str)-1; } if((str.Find("//") != -1)&&(str.Find("//_") == -1)) { str.TrimLeft("//"); str.Remove('\n'); str.Remove('\r'); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].strCOMMENT = str; } if((str.Find("PRIBOR") != -1)&&(str.Find("MAKE_PRIBOR") == -1)&&(str.Find("NUMBER_OF_PRIBOR") == -1)) { str.TrimLeft("PRIBOR"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].PRIBOR = atoi(str); } if((str.Find("ADRESS") != -1)&&(str.Find("START_ADRESS") == -1)&&(str.Find("ADRESS_PMZ") == -1)) { str.TrimLeft("ADRESS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].ADRESS = atoi(str); } if(str.Find("FUNCTION") != -1) { str.TrimLeft("FUNCTION"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].FUNCTION = atoi(str); } if(str.Find("START_ADRESS") != -1) { str.TrimLeft("START_ADRESS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].START_ADRESS = atoi(str); } if(str.Find("ADRESS_PMZ") != -1) { str.TrimLeft("ADRESS_PMZ"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].ADRESS_PMZ = atoi(str); } if((str.Find("NUMBER") != -1)&&(str.Find("NUMBER_NO_ANSWER") == -1)&&(str.Find("NUMBER_OF_PRIBOR") == -1)) { str.TrimLeft("NUMBER"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].NUMBER = atoi(str); } if(str.Find("DOP_BYTE1") != -1) { str.TrimLeft("DOP_BYTE1"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].DOP_BYTE1 = atoi(str); } if(str.Find("DOP_BYTE2") != -1) { str.TrimLeft("DOP_BYTE2"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].DOP_BYTE2 = atoi(str); } if(str.Find("DOP_BYTE3") != -1) { str.TrimLeft("DOP_BYTE3"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].DOP_BYTE3 = atoi(str); } if(str.Find("DOP_BYTE4") != -1) { str.TrimLeft("DOP_BYTE4"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].DOP_BYTE4 = atoi(str); } if(str.Find("TYPE_STATUS") != -1) { str.TrimLeft("TYPE_STATUS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].TYPE_STATUS= atoi(str); } if(str.Find("MASKA_STATUS") != -1) { str.TrimLeft("MASKA_STATUS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].MASKA_STATUS= atoi(str); } if(str.Find("ADRES_STATUS") != -1) { str.TrimLeft("ADRES_STATUS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].ADRES_STATUS= atoi(str); } if(str.Find("ADRES_4B") != -1) { str.TrimLeft("ADRES_4B"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_ModbusPriborArray.GetSize())) m_ModbusPriborArray[nProcIndex].ADRES_4B= atoi(str); } strBuf.Delete(0,nIndex+1); }while(nIndex != -1); } catch(...) { return FALSE; } return TRUE; }
BOOL CModbusM::SaveToFile(CString strFile) { CString strBuf,str; str.Format("PORT=%d\r\n",PORT); strBuf+=str; str.Format("BAUDRATE=%d\r\n",BAUDRATE); strBuf+=str; str.Format("STOPBITS=%d\r\n",STOPBITS); strBuf+=str; str.Format("PARITY=%d\r\n",PARITY); strBuf+=str; str.Format("BYTETIME=%d\r\n",BYTETIME); strBuf+=str; str.Format("WAITRESP=%d\r\n",WAITRESP); strBuf+=str; str.Format("NEXTMESSAGE=%d\r\n",NEXTMESSAGE); strBuf+=str; str.Format("NUMBER_OF_PRIBOR=%d\r\n",m_ModbusPriborArray.GetSize()); strBuf+=str; str.Format("AMOUNTBYTE=%d\r\n",AMOUNTBYTE); strBuf+=str; str.Format("CONTROLPOTOK=%d\r\n",CONTROLPOTOK); strBuf+=str; str.Format("NUMBER_NO_ANSWER=%d\r\n",NUMBER_NO_ANSWER); strBuf+=str; str.Format("MODBUS_TYPE=%d\r\n\r\n",MODBUS_TYPE); strBuf+=str; for(int i =0; i < m_ModbusPriborArray.GetSize(); i++) { str.Format("MAKE_PRIBOR=%d\r\n",i+1); strBuf+=str; str.Format("PRIBOR=%d\r\n",m_ModbusPriborArray[i].PRIBOR); strBuf+=str; str.Format("ADRESS=%d\r\n",m_ModbusPriborArray[i].ADRESS); strBuf+=str; str.Format("FUNCTION=%d\r\n",m_ModbusPriborArray[i].FUNCTION); strBuf+=str; str.Format("START_ADRESS=%d\r\n",m_ModbusPriborArray[i].START_ADRESS); strBuf+=str; str.Format("NUMBER=%d\r\n",m_ModbusPriborArray[i].NUMBER); strBuf+=str; str.Format("ADRESS_PMZ=%d\r\n",m_ModbusPriborArray[i].ADRESS_PMZ); strBuf+=str; str.Format("DOP_BYTE1=%d\r\n",m_ModbusPriborArray[i].DOP_BYTE1); strBuf+=str; str.Format("DOP_BYTE2=%d\r\n",m_ModbusPriborArray[i].DOP_BYTE2); strBuf+=str; str.Format("DOP_BYTE3=%d\r\n",m_ModbusPriborArray[i].DOP_BYTE3); strBuf+=str; str.Format("DOP_BYTE4=%d\r\n",m_ModbusPriborArray[i].DOP_BYTE4); strBuf+=str; str.Format("TYPE_STATUS=%d\r\n",m_ModbusPriborArray[i].TYPE_STATUS); strBuf+=str; str.Format("MASKA_STATUS=%d\r\n",m_ModbusPriborArray[i].MASKA_STATUS); strBuf+=str; str.Format("ADRES_STATUS=%d\r\n",m_ModbusPriborArray[i].ADRES_STATUS); strBuf+=str; str.Format("ADRES_4B=%d\r\n",m_ModbusPriborArray[i].ADRES_4B); strBuf+=str; str.Format("//%s\r\n\r\n",m_ModbusPriborArray[i].strCOMMENT); strBuf+=str; } CFile f; try { f.Open(strFile,CFile::modeCreate|CFile::modeWrite); f.Write((void*)strBuf.GetBuffer(),strBuf.GetLength()); f.Close(); } catch(...) { return FALSE; } return TRUE; }
/*! @brief このメソッドは WM_INITDIALOG のメッセージに応答して呼び出されます。 */ BOOL CInspectUsefulToolsDlg::OnInitDialog() { CDialog::OnInitDialog(); // このダイアログのアイコンを設定します。アプリケーションのメイン ウィンドウがダイアログでない場合、 // Framework は、この設定を自動的に行います。 SetIcon(m_hIcon, TRUE); // 大きいアイコンの設定 //SetIcon(m_hIcon, FALSE); // 小さいアイコンの設定 // メニューの初期化 InitializeMenuTree(); InitializeContents(); // タイトルの設定 CString strAppName = CString((LPCTSTR)IDS_APP_NAME); this->SetWindowText(strAppName); CLSID clsid; if (CLSIDFromProgID(OLESTR("Excel.Application"), &clsid) == NOERROR){ // Excel がインストールされている LPUNKNOWN lpUnk; HRESULT hr; LPDISPATCH lpDispatch; BOOL bOpenExcel = FALSE; if (GetActiveObject(clsid, NULL, &lpUnk) == NOERROR){ hr = lpUnk->QueryInterface(IID_IDispatch, (LPVOID*)&lpDispatch); lpUnk->Release(); if (hr == NOERROR) { //すでにExcelが起動されている状態であればAttachDispatch m_inXLApp.AttachDispatch(lpDispatch,TRUE); bOpenExcel = TRUE; } } if (m_inXLApp.m_lpDispatch == NULL) { bOpenExcel = m_inXLApp.CreateDispatch(clsid); m_bOpenXL = TRUE; } if (bOpenExcel == TRUE) { // Excelファイルの初期化 CWorkbooks inWorkbooks = m_inXLApp.get_Workbooks(); COleVariant varNull; varNull.ChangeType(VT_NULL); HRSRC hrSrc = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDR_MACRO_EXCEL_RCDATA), RT_RCDATA); if (hrSrc != NULL) { HGLOBAL hGlobal = LoadResource(AfxGetApp()->m_hInstance, hrSrc); if (hGlobal != NULL) { char *rcData = (char *)LockResource(hGlobal); /* リソースサイズの取得 */ DWORD dwSize = SizeofResource(AfxGetApp()->m_hInstance, hrSrc); TCHAR szFilePath[MAX_PATH]; GetTempPath(MAX_PATH, szFilePath); TCHAR szFileName[MAX_PATH]; GetTempFileName(szFilePath, _T("SubTools_"), 0, szFileName); CFile inFile; inFile.Open(szFileName, CFile::modeWrite); inFile.Write(rcData, dwSize); inFile.Close(); strTempFilePath = szFileName; m_inXLBook = inWorkbooks.Open(szFileName , varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull, varNull,varNull, varNull); m_bOpenBook = TRUE; } } } } return TRUE; }
void CMainFrame::Scan() { CView *pView = GetActiveView(); //获取当前VIEW视图 CDC *pDC = pView->GetDC(); //得到VIEW的DC CString cs; cs.Format("%d",Scan_num+1); pDC->TextOut(0,Height/2,cs,cs.GetLength()); pView->ReleaseDC(pDC); int i,k; unsigned char MAX=0; int MAX_i=0; unsigned char seq[3]; float peak; float distance; float Phi; //float Theta; float Z; float L1,L2,L3,L4; float r; uchar* ptr; HVSTATUS status =STATUS_OK; /********采集单帧图像**********/ unsigned char *ppbuffer[1]; ppbuffer[0]=m_pRawBuffer; status =HVSnapShot(m_hhv,ppbuffer,1); HV_VERIFY(status); /********显示当前帧************/ OnSnapChange(NULL,NULL); //生成支持OPENCV的IPLIMAGE数据结构,并使用相机采集的图像数据初始化// CvSize cvSize; cvSize.width = Width; cvSize.height = Height; IplImage *iplImage = cvCreateImageHeader(cvSize,IPL_DEPTH_8U,3); cvSetData(iplImage,m_pImageBuffer,Width*3); //申请灰度空间,将BGR格式转化为灰度数据 IplImage *iplgray = cvCreateImage(cvGetSize(iplImage),IPL_DEPTH_8U,1); cvCvtColor(iplImage,iplgray,CV_BGR2GRAY); for(k=0;k<Height;k++) { ptr=(uchar*)(iplgray->imageData+k*iplgray->widthStep); for(i=0;i<Width;i++) for(i=0;i<Width;i++) { if( ptr[i]>=MAX) { MAX=ptr[i]; MAX_i=i; } } if(MAX<=50) { Scan_result[Scan_num][k].X=0; Scan_result[Scan_num][k].Y=0; Scan_result[Scan_num][k].Z=0; continue; } if(MAX_i<=1) seq[2]=0; else seq[2]=ptr[MAX_i-1]; seq[1]=ptr[MAX_i]; if(MAX_i>=Width) seq[0]=0; else seq[0]=ptr[MAX_i+1]; //peak=1/2*(log(seq[0])-log(seq[2]))/(log(seq[0])-2*log(seq[1])+log(seq[2]))+Width-MAX_i; peak=(seq[2]-seq[0])/(seq[0]+seq[1]+seq[2])+Width-MAX_i; //peak=(2*ptr[MAX_i-2]+ptr[MAX_i-1]-ptr[MAX_i+1]-2*ptr[MAX_i+2])/(ptr[MAX_i+2]+ptr[MAX_i+1]+ptr[MAX_i]+ptr[MAX_i-1]+ptr[MAX_i-2])+Width-MAX_i; /************************计算某行扫描结果*****************************************/ distance=FS/(PIX_SIZE*peak+ PIX_OFF)+DIST_OFF; if(distance>1800) { Scan_result[Scan_num][k].X=0; Scan_result[Scan_num][k].Y=0; Scan_result[Scan_num][k].Z=0; continue; } //Theta=atan((k-Height/2)*PIX_SIZE/f); Z=(distance-DIST_OFF)*(Height/2-k)*PIX_SIZE/f; L1=sqrt(distance*distance+Z*Z); L3= distance*tan(PI/2- LaserAngle); L2= sqrt(L1*L1+L3*L3); L4= sqrt(L3*L3+distance*distance); r= sqrt( (L3-rotation_r)*(L3-rotation_r)+distance*distance); Phi=Scan_num*Scan_step+PI/2-acos( (rotation_r*rotation_r+r*r-L4*L4)/2.0f/rotation_r/r); Scan_result[Scan_num][k].X=r*cos(Phi); Scan_result[Scan_num][k].Y=r*sin(Phi); Scan_result[Scan_num][k].Z=Z; /****************************************************************************/ } cvReleaseImage(&iplgray); /************如果扫描完成,关闭串口,并输出数据********/ if(Scan_num==Scan_total-1) { MessageBox("扫描完成"); Scan_num=0; OnBtnSend('2'); //OnBtnSend('2'); sio_close(Port); //关闭串口 /*************数据输出**************/ char* fileName=dataout; CString strtemp; CFile file; CFileException fileException; if(!file.Open(fileName,CFile::modeCreate | CFile::modeWrite, &fileException)) { CString errorInfo; errorInfo.Format("不能打开文件%s,错误:%u\n",fileName,fileException.m_cause); MessageBox(errorInfo,"错误",MB_OK|MB_ICONERROR); return; } for(i=0;i<Scan_total;i++) for(k=0;k<Height;k++) { if(Scan_result[i][k].X==0 & Scan_result[i][k].Y==0 & Scan_result[i][k].Z==0) continue; else { strtemp.Format("%.3f, %.3f, %.3f\r\n\r\n",Scan_result[i][k].X,Scan_result[i][k].Y,Scan_result[i][k].Z); file.Write(strtemp,strtemp.GetLength()); } } file.Close(); MessageBox("已成功输出数据","信息",MB_OK|MB_ICONINFORMATION); return; } /**********扫描未完成,发送串口指令***********/ else { OnBtnSend('1'); //OnBtnSend('1'); Scan_num=Scan_num+1; } }
hmp_file *hmp_open(const char *filename, int bUseD1Hog) { int i; char buf [256]; long data = 0; CFile cf; hmp_file *hmp; int num_tracks, midi_div; ubyte *p; if (!cf.Open (filename, gameFolders.szDataDir, "rb", bUseD1Hog)) return NULL; hmp = new hmp_file; if (!hmp) { cf.Close(); return NULL; } memset(hmp, 0, sizeof(*hmp)); if ((cf.Read (buf, 1, 8) != 8) || (memcmp(buf, "HMIMIDIP", 8))) goto err; if (cf.Seek (0x30, SEEK_SET)) goto err; if (cf.Read (&num_tracks, 4, 1) != 1) goto err; if (cf.Seek (0x38, SEEK_SET)) goto err; if (cf.Read (&midi_div, 4, 1) != 1) goto err; if ((num_tracks < 1) || (num_tracks > HMP_TRACKS)) goto err; hmp->num_trks = num_tracks; hmp->midi_division = midi_div; hmp->tempo = 120; if (cf.Seek(0x308, SEEK_SET)) goto err; for (i = 0; i < num_tracks; i++) { if ((cf.Seek(4, SEEK_CUR)) || (cf.Read(&data, 4, 1) != 1)) goto err; data -= 12; #if 0 if (i == 0) /* track 0: reserve length for tempo */ data += sizeof(hmp_tempo); #endif hmp->trks [i].len = data; if (!(p = hmp->trks [i].data = new ubyte [data])) goto err; #if 0 if (i == 0) { /* track 0: add tempo */ memcpy(p, hmp_tempo, sizeof(hmp_tempo)); p += sizeof(hmp_tempo); data -= sizeof(hmp_tempo); } #endif /* finally, read track data */ if ((cf.Seek(4, SEEK_CUR)) || (cf.Read(p, data, 1) != 1)) goto err; } cf.Close(); return hmp; err: cf.Close(); hmp_close(hmp); return NULL; }
//上传头像 bool CDataBaseSink::OnRequestUploadFace(WORD wRequestID, DWORD dwContextID, VOID * pData, WORD wDataSize) { //数据验证 ASSERT(wDataSize==sizeof(DBR_GP_UploadCustomFace)); if (wDataSize!=sizeof(DBR_GP_UploadCustomFace)) return false; //数据转换 DBR_GP_UploadCustomFace *pUploadCustomFace = (DBR_GP_UploadCustomFace*)pData; //文件定义 CFile fileCustomFace; TCHAR szFileName[128]; _snprintf(szFileName, CountArray(szFileName), TEXT("%s\\UploadFile_%ld.zip"), theApp.m_szDirWork, pUploadCustomFace->dwUserID); try { if ( fileCustomFace.Open( szFileName, CFile::modeRead|CFile::typeBinary) ) { BYTE cbCustomFaceData[1024*30]; //读取文件 UINT uReadSize = fileCustomFace.Read(cbCustomFaceData, CountArray(cbCustomFaceData)); //关闭文件 fileCustomFace.Close(); LONG lRet=-1; try { lRet = SPUploadFace(pUploadCustomFace->dwUserID, cbCustomFaceData, uReadSize); } catch (IDataBaseException * pIException) { //错误信息 LPCTSTR pszDescribe=pIException->GetExceptionDescribe(); CTraceService::TraceString(pszDescribe,TraceLevel_Exception); } //成功判断 if ( lRet != -1 ) { DBR_GP_UploadFaceResult UploadFaceResult; ZeroMemory(&UploadFaceResult, sizeof(UploadFaceResult)); lstrcpyn(UploadFaceResult.szDescribeMsg, TEXT("头像上传成功!"), sizeof(UploadFaceResult.szDescribeMsg)); UploadFaceResult.dwFaceVer=lRet; UploadFaceResult.bOperateSuccess=true; m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_UPLOAD_FACE_RESULT,dwContextID, &UploadFaceResult,sizeof(UploadFaceResult)); } else { //操作失败 DBR_GP_UploadFaceResult UploadFaceResult; ZeroMemory(&UploadFaceResult, sizeof(UploadFaceResult)); lstrcpyn(UploadFaceResult.szDescribeMsg, TEXT("由于数据库操作异常,请重新上传!"), sizeof(UploadFaceResult.szDescribeMsg)); UploadFaceResult.bOperateSuccess=false; m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_UPLOAD_FACE_RESULT,dwContextID, &UploadFaceResult,sizeof(UploadFaceResult)); } //删除文件 CFile::Remove(szFileName); } } catch(...) {} return true; }
bool CPlayListPLS::Load(const std::string &strFile) { //read it from the file std::string strFileName(strFile); m_strPlayListName = URIUtils::GetFileName(strFileName); Clear(); bool bShoutCast = false; if( StringUtils::StartsWithNoCase(strFileName, "shout://") ) { strFileName.replace(0, 8, "http://"); m_strBasePath = ""; bShoutCast = true; } else URIUtils::GetParentPath(strFileName, m_strBasePath); CFile file; if (!file.Open(strFileName) ) { file.Close(); return false; } if (file.GetLength() > 1024*1024) { CLog::Log(LOGWARNING, "%s - File is larger than 1 MB, most likely not a playlist",__FUNCTION__); return false; } char szLine[4096]; std::string strLine; // run through looking for the [playlist] marker. // if we find another http stream, then load it. while (1) { if ( !file.ReadString(szLine, sizeof(szLine) ) ) { file.Close(); return size() > 0; } strLine = szLine; StringUtils::Trim(strLine); if(StringUtils::EqualsNoCase(strLine, START_PLAYLIST_MARKER)) break; // if there is something else before playlist marker, this isn't a pls file if(!strLine.empty()) return false; } bool bFailed = false; while (file.ReadString(szLine, sizeof(szLine) ) ) { strLine = szLine; StringUtils::RemoveCRLF(strLine); size_t iPosEqual = strLine.find("="); if (iPosEqual != std::string::npos) { std::string strLeft = strLine.substr(0, iPosEqual); iPosEqual++; std::string strValue = strLine.substr(iPosEqual); StringUtils::ToLower(strLeft); StringUtils::TrimLeft(strLeft); if (strLeft == "numberofentries") { m_vecItems.reserve(atoi(strValue.c_str())); } else if (StringUtils::StartsWith(strLeft, "file")) { vector <int>::size_type idx = atoi(strLeft.c_str() + 4); if (!Resize(idx)) { bFailed = true; break; } // Skip self - do not load playlist recursively if (StringUtils::EqualsNoCase(URIUtils::GetFileName(strValue), URIUtils::GetFileName(strFileName))) continue; if (m_vecItems[idx - 1]->GetLabel().empty()) m_vecItems[idx - 1]->SetLabel(URIUtils::GetFileName(strValue)); CFileItem item(strValue, false); if (bShoutCast && !item.IsAudio()) strValue.replace(0, 7, "shout://"); strValue = URIUtils::SubstitutePath(strValue); CUtil::GetQualifiedFilename(m_strBasePath, strValue); g_charsetConverter.unknownToUTF8(strValue); m_vecItems[idx - 1]->SetPath(strValue); } else if (StringUtils::StartsWith(strLeft, "title")) { vector <int>::size_type idx = atoi(strLeft.c_str() + 5); if (!Resize(idx)) { bFailed = true; break; } g_charsetConverter.unknownToUTF8(strValue); m_vecItems[idx - 1]->SetLabel(strValue); } else if (StringUtils::StartsWith(strLeft, "length")) { vector <int>::size_type idx = atoi(strLeft.c_str() + 6); if (!Resize(idx)) { bFailed = true; break; } m_vecItems[idx - 1]->GetMusicInfoTag()->SetDuration(atol(strValue.c_str())); } else if (strLeft == "playlistname") { m_strPlayListName = strValue; g_charsetConverter.unknownToUTF8(m_strPlayListName); } } } file.Close(); if (bFailed) { CLog::Log(LOGERROR, "File %s is not a valid PLS playlist. Location of first file,title or length is not permitted (eg. File0 should be File1)", URIUtils::GetFileName(strFileName).c_str()); return false; } // check for missing entries ivecItems p = m_vecItems.begin(); while ( p != m_vecItems.end()) { if ((*p)->GetPath().empty()) { p = m_vecItems.erase(p); } else { ++p; } } return true; }
// 转换RGB void CRGB2YUVView::OnConvertPAL() { CDC *pDC = GetDC(); CRect rect; CBrush brush(RGB(128,128,128)); GetClientRect(&rect); pDC->FillRect(&rect, &brush); // PAL 720x576 : 中国的电视标准为PAL制 int CurrentXRes = 720; int CurrentYRes = 576; int size = CurrentXRes * CurrentYRes; // 分配内存 byte *Video_Field0 = (byte*)malloc(CurrentXRes*CurrentYRes); byte *Video_Field1 = (byte*)malloc(CurrentXRes*CurrentYRes); // 保存内存指针 byte *Video_Field0_ = Video_Field0; byte *Video_Field1_ = Video_Field1; byte yuv_y0, yuv_u0, yuv_v0, yuv_v1; // {y0, u0, v0, v1}; byte bufRGB[3]; // 临时保存{R,G,B} byte bufYUV[3]; // 临时保存{Y,U,V} // 初始化数组空间 ZeroMemory(bufRGB, sizeof(byte)*3); ZeroMemory(bufYUV, sizeof(byte)*3); // 初始化内存 ZeroMemory(Video_Field0, CurrentXRes*CurrentYRes); ZeroMemory(Video_Field1, CurrentXRes*CurrentYRes); // BMP 位图操作 BITMAPFILEHEADER bmfh; BITMAPINFOHEADER bmih; char strFileName[MAX_PATH]="720bmp.bmp"; CFile* f; f = new CFile(); f->Open(strFileName, CFile::modeRead); f->SeekToBegin(); f->Read(&bmfh, sizeof(bmfh)); f->Read(&bmih, sizeof(bmih)); // 分配图片像素内存 RGBTRIPLE *rgb; rgb = new RGBTRIPLE[bmih.biWidth*bmih.biHeight]; f->SeekToBegin(); f->Seek(54,CFile::begin); // BMP 54个字节之后的是位像素数据 f->Read(rgb, bmih.biWidth * bmih.biHeight * 3); // 这里只读24位RGB(r,g,b)图像 // 上场 (1,3,5,7...行) for (int i = bmih.biHeight-1; i>=0; i--) { for (int j = 0; j<bmih.biWidth; j++) { if(!(i%2)==0) { bufRGB[0] = rgb[i*bmih.biWidth+j].rgbtRed; // R bufRGB[1] = rgb[i*bmih.biWidth+j].rgbtGreen; // G bufRGB[2] = rgb[i*bmih.biWidth+j].rgbtBlue; // B // RGB转换为YUV RGB2YUV(bufRGB,bufYUV); yuv_y0 = bufYUV[0]; // y yuv_u0 = bufYUV[1]; // u yuv_v0 = bufYUV[2]; // v for (int k=0; k<1000; k++) ; //延时 // 视图中显示 pDC->SetPixel(j, (bmih.biHeight-1)-i, RGB(bufRGB[0], bufRGB[1], bufRGB[2])); // UYVY标准 [U0 Y0 V0 Y1] [U1 Y2 V1 Y3] [U2 Y4 V2 Y5] 每像素点两个字节,[内]为四个字节 if ((j%2)==0) { *Video_Field0 = yuv_u0; Video_Field0++; yuv_v1 = yuv_v0; // v保存起来供下一字节使用 } else { *Video_Field0 = yuv_v1; Video_Field0++; } *Video_Field0 = yuv_y0; Video_Field0++; }// end if i%2 } } // 下场 (2,4,6,8...行) for (int i_ = bmih.biHeight-1; i_>=0; i_--) { for (int j_ = 0; j_<bmih.biWidth; j_++) { if((i_%2)==0) { bufRGB[0] = rgb[i_*bmih.biWidth+j_].rgbtRed; // R bufRGB[1] = rgb[i_*bmih.biWidth+j_].rgbtGreen; // G bufRGB[2] = rgb[i_*bmih.biWidth+j_].rgbtBlue; // B // RGB转换为YUV RGB2YUV(bufRGB,bufYUV); yuv_y0 = bufYUV[0]; // y yuv_u0 = bufYUV[1]; // u yuv_v0 = bufYUV[2]; // v for (int k=0; k<1000; k++) ; //延时 // 视图中显示 pDC->SetPixel(j_, (bmih.biHeight-1)-i_, RGB(bufRGB[0], bufRGB[1], bufRGB[2])); // UYVY标准 [U0 Y0 V0 Y1] [U1 Y2 V1 Y3] [U2 Y4 V2 Y5] 每像素点两个字节,[内]为四个字节 if ((j_%2)==0) { *Video_Field1 = yuv_u0; Video_Field1++; yuv_v1 = yuv_v0; // v保存起来供下一字节使用 } else { *Video_Field1 = yuv_v1; Video_Field1++; } *Video_Field1 = yuv_y0; Video_Field1++; } } } // 关闭BMP位图文件 f->Close(); WriteYUV(Video_Field0_, Video_Field1_, size); // 释放内存 free( Video_Field0_ ); free( Video_Field1_ ); delete f; delete rgb; }
int KiesBNR::SMemoFiletoDecode(char* inputPath, char* outputPath){ CString inputPathString = (CString)inputPath; if(!PathFileExists((LPCWSTR)inputPathString)) return 0; UINT XMLDataOffset = 0; CFile input; if ( !input.Open((LPCWSTR)inputPathString, CFile::modeRead | CFile::modeNoTruncate | CFile::typeBinary) ) { return false; } //XML 데이터 크기만큼의 버퍼 생성; int nBufSize = input.GetLength(); char* XMLData = new char[nBufSize+1]; ZeroMemory(XMLData, nBufSize+1); //버퍼에 XML 내용을 읽어들인다.; input.Seek(XMLDataOffset, input.begin); input.Read(XMLData, nBufSize+1); //XML 데이터가 NULL일경우 False 반환; if (XMLData == NULL) return false; //메모리상에 있는 XML 데이터를 오픈 (Parse); TiXmlDocument m_Document; m_Document.Parse(XMLData); // xml open // 루트노드 접근.; TiXmlElement* pRoot = m_Document.FirstChildElement("SMemoItems"); if (!pRoot) goto END_PROCESS; // 값을 읽고자 하는 Welcome 엘리먼트로 접근.; TiXmlElement* pElem = pRoot->FirstChildElement("Items")->FirstChildElement(); if (!pElem) goto END_PROCESS; while(pElem) { CString str1 = _T(""); CString str2 = _T(""); CString str3 = _T(""); CString str4 = _T(""); CString element = _T(""); DWORD str_Len = 0; TCHAR * dstTCHAR = NULL; char *psNode = (char*)pElem->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL); dstTCHAR = new TCHAR[str_Len + 1]; memset(dstTCHAR, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len); element.Format(L"%s",dstTCHAR); delete [] dstTCHAR; if(element.Find(L"SMemoItem")!=-1)//SMemoItem이 들어옴.. { TiXmlElement* pElem_1=pElem->FirstChildElement(); while(pElem_1) { CString str_1=_T(""); CString element_1=_T(""); DWORD str_Len_1 = 0; TCHAR * dstTCHAR_1 = NULL; char *psNode_1 = (char*)pElem_1->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL); dstTCHAR_1 = new TCHAR[str_Len + 1]; memset(dstTCHAR_1, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len); element_1.Format(L"%s",dstTCHAR_1); delete [] dstTCHAR_1; if(element_1.Find(_T("RecordID"))!= -1){ TCHAR* dstTch1 = NULL; const char *text = pElem_1->GetText(); if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch1 = new TCHAR[str_Len + 1]; memset(dstTch1, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch1, str_Len); str1.Format((L"%s"),dstTch1); delete [] dstTch1; }else if(element_1.Find(_T("CreateDate"))!= -1){ TCHAR* dstTch2 = NULL; const char *text = pElem_1->GetText(); if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch2 = new TCHAR[str_Len + 1]; memset(dstTch2, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch2, str_Len); str2.Format((L"%s"),dstTch2); str2.Format((L"%s"),UnixTimeToStrTime(str2.Left(10))); delete [] dstTch2; }else if(element_1.Find(_T("ModifiedDate"))!= -1){ TCHAR* dstTch3 = NULL; const char *text = pElem_1->GetText(); if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch3 = new TCHAR[str_Len + 1]; memset(dstTch3, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch3, str_Len); str3.Format((L"%s"),dstTch3); str3.Format((L"%s"),UnixTimeToStrTime(str3.Left(10))); delete [] dstTch3; }else if((element_1.Right(8) == _T("Location") )) { TCHAR* dstTch4 = NULL; const char *text = pElem_1->GetText(); if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch4 = new TCHAR[str_Len + 1]; memset(dstTch4, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch4, str_Len); str4.Format((L"%s"),dstTch4); delete []dstTch4; }else if(element_1.Find(_T("LocationDecode"))!= -1){ const char *text = pElem_1->GetText(); if(text == NULL){ stSMemoXml.recordID = str1; stSMemoXml.createDate = str2; stSMemoXml.modifiedDate = str3; stSMemoXml.location_ = str4; stSMemoXml.locationDecode = L"NULL"; mSMemoXml.insert(pair_SMemoXml(stSMemoXml.recordID, stSMemoXml)); stSMemoXml.recordID.Empty(); stSMemoXml.createDate.Empty(); stSMemoXml.modifiedDate.Empty(); stSMemoXml.location_.Empty(); stSMemoXml.locationDecode.Empty(); break; } std::string cipher(text); PBYTE buf_cipher_ = (PBYTE)malloc(cipher.size()+1); buf_cipher_[cipher.size()] = 0x00; memcpy(buf_cipher_, cipher.c_str(), cipher.size()); INT length = base64_decode((PCHAR)buf_cipher_, (unsigned char*)buf_cipher_, cipher.size()-8 ); wchar_t *patt[4] = {L"<ThumbData>", L"<Text>", L"</ThumbData>", L"</Text>"}; wchar_t strUnicode[256] = {0,}; for(int i = 0 ; i < 2 ; i++){ long startOffset = ps.patternFind((char*)buf_cipher_, length, 0, (char *)patt[i], wcslen(patt[i])*2, pattern_sp::eMethod_KMP) + wcslen(patt[i])*2; long endOffset = ps.patternFind((char*)buf_cipher_, length, 0, (char *)patt[i+2], wcslen(patt[i+2])*2, pattern_sp::eMethod_KMP); char* buf;int sizes = endOffset - startOffset; buf = new char[sizes]; memcpy_s( buf, sizes, (char*)(buf_cipher_+startOffset), sizes ); for(int a = 0 ; a < sizes ; a+=2){ buf[a/2] = buf[a]; } int halfsize = sizes/2; INT length2 = base64_decode(buf, (unsigned char*)buf, halfsize ); if(i == 0){ CFile file_; CString PNGFileName = NULL; PNGFileName.Format(L"%s%s%s", (CString)outputPath, str1, L"_memo.png"); if ( !PathFileExists(PNGFileName) ) { if( file_.Open( PNGFileName, CFile::modeCreate | CFile::modeWrite ) == FALSE ) return FALSE; file_.Write(buf,sizes/2); file_.Close(); } }else{ //int nLen = MultiByteToWideChar(CP_UTF8, 0, (const char*)buf, strlen((char*)buf), NULL, NULL); //MultiByteToWideChar(CP_UTF8, 0, (const char*)buf, strlen((const char*)buf), strUnicode, strlen((char*)buf)+10);// utf-8 to unicode } delete []buf; } stSMemoXml.recordID = str1; stSMemoXml.createDate = str2; stSMemoXml.modifiedDate = str3; stSMemoXml.location_ = str4; stSMemoXml.locationDecode = L""; mSMemoXml.insert(pair_SMemoXml(stSMemoXml.recordID, stSMemoXml)); stSMemoXml.recordID.Empty(); stSMemoXml.createDate.Empty(); stSMemoXml.modifiedDate.Empty(); stSMemoXml.location_.Empty(); stSMemoXml.locationDecode.Empty(); } pElem_1 = pElem_1->NextSiblingElement(); } } pElem = pElem->NextSiblingElement(); } END_PROCESS: m_Document.Clear(); if(XMLData) delete XMLData; CreateWriteSMemoXmlCSVFile((CString)outputPath); return 1; }
int KiesBNR::OtherFilestoDecode(char* inputPath, char* outputPath, char* fileName){ //Read Input File CString inputPathString = (CString)inputPath; if(!PathFileExists((LPCWSTR)inputPathString)) return 0; UINT XMLDataOffset = 0; CFile input; if ( !input.Open((LPCWSTR)inputPathString, CFile::modeRead | CFile::modeNoTruncate | CFile::typeBinary) ) { return false; } //XML 데이터 크기만큼의 버퍼 생성; int nBufSize = input.GetLength(); char* XMLData = new char[nBufSize+1]; ZeroMemory(XMLData, nBufSize+1); //버퍼에 XML 내용을 읽어들인다.; input.Seek(XMLDataOffset, input.begin); input.Read(XMLData, nBufSize+1); //XML 데이터가 NULL일경우 False 반환; if (XMLData == NULL) return false; //메모리상에 있는 XML 데이터를 오픈 (Parse); TiXmlDocument m_Document; m_Document.Parse(XMLData); // xml open // 루트노드 접근.; TiXmlElement* pRoot = m_Document.FirstChildElement("MtpUtilItems"); if (!pRoot) goto END_PROCESS; // 값을 읽고자 하는 Welcome 엘리먼트로 접근.; TiXmlElement* pElem = pRoot->FirstChildElement("Items")->FirstChildElement(); if (!pElem) goto END_PROCESS; while(pElem) { CString str1=_T(""); CString element=_T(""); DWORD str_Len = 0; TCHAR * dstTCHAR = NULL; char *psNode = (char*)pElem->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL); dstTCHAR = new TCHAR[str_Len + 1]; memset(dstTCHAR, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len); element.Format(L"%s",dstTCHAR); delete [] dstTCHAR; if(element.Find(L"MtpUtilItem")!=-1) { TiXmlElement* pElem_1=pElem->FirstChildElement(); while(pElem_1) { CString str_1=_T(""); CString element_1=_T(""); DWORD str_Len_1 = 0; TCHAR * dstTCHAR_1 = NULL; char *psNode_1 = (char*)pElem_1->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL); dstTCHAR_1 = new TCHAR[str_Len + 1]; memset(dstTCHAR_1, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len); element_1.Format(L"%s",dstTCHAR_1); delete [] dstTCHAR_1; if(element_1.Find(_T("FileContent"))!= -1){ TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str1.Format((L"%s"),dstTch); delete [] dstTch; //base64 Decoding string cipher(text); PBYTE buf_cipher = (PBYTE)malloc(cipher.size()+1); buf_cipher[cipher.size()] = 0x00; memcpy(buf_cipher, cipher.c_str(), cipher.size()); INT length = base64_decode((PCHAR)buf_cipher, buf_cipher, cipher.size()); strcat_s(outputPath, strlen(outputPath)+8, "Decode_"); strcat_s(outputPath, strlen(outputPath)+strlen(fileName)+1, fileName); CFile decodefileoutput; if ( !PathFileExists((CString)outputPath) ) { if( decodefileoutput.Open((CString)outputPath, CFile::modeCreate | CFile::modeWrite ) == FALSE) return FALSE; decodefileoutput.Write(buf_cipher, length); decodefileoutput.Close(); } CArkLib ark; if(ark.Create(ARK_DLL_RELEASE_FILE_NAME)!=ARKERR_NOERR) return 0; if(ark.Open(outputPath) == FALSE) return 0; int len = strlen(outputPath)+2; strcat_s(outputPath, len + 2, "_"); ark.ExtractAllTo(outputPath); ark.Destroy(); } pElem_1 = pElem_1->NextSiblingElement(); } } pElem = pElem->NextSiblingElement(); } END_PROCESS: m_Document.Clear(); if(XMLData) delete XMLData; return 1; }
int KiesBNR::MessageFiletoDecode(char* inputPath, char* outputPath){ //Read Input File CString inputPathString = (CString)inputPath; if(!PathFileExists((LPCWSTR)inputPathString)) return 0; UINT XMLDataOffset = 0; CFile input; if ( !input.Open((LPCWSTR)inputPathString, CFile::modeRead | CFile::modeNoTruncate | CFile::typeBinary) ) { return false; } //XML 데이터 크기만큼의 버퍼 생성; int nBufSize = input.GetLength(); char* XMLData = new char[nBufSize+1]; ZeroMemory(XMLData, nBufSize+1); //버퍼에 XML 내용을 읽어들인다.; input.Seek(XMLDataOffset, input.begin); input.Read(XMLData, nBufSize+1); //XML 데이터가 NULL일경우 False 반환; if (XMLData == NULL) return false; //메모리상에 있는 XML 데이터를 오픈 (Parse); TiXmlDocument m_Document; m_Document.Parse(XMLData); // xml open // 루트노드 접근.; TiXmlElement* pRoot = m_Document.FirstChildElement("MessageData"); if (!pRoot) goto END_PROCESS; // 값을 읽고자 하는 Welcome 엘리먼트로 접근.; TiXmlElement* pElem = pRoot->FirstChildElement("SMSList")->FirstChildElement(); TiXmlElement* pElem2 = pRoot->FirstChildElement("MMSList")->FirstChildElement();//HextoString if (!pElem) goto END_PROCESS; while(pElem) { CString str1=_T(""); CString str2=_T(""); CString str3=_T(""); CString str4=_T(""); CString element=_T(""); DWORD str_Len = 0; TCHAR * dstTCHAR = NULL; char *psNode = (char*)pElem->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL); dstTCHAR = new TCHAR[str_Len + 1]; memset(dstTCHAR, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len); element.Format(L"%s",dstTCHAR); delete [] dstTCHAR; if(element.Find(L"SMSStoreItem") != -1) { TiXmlElement* pElem_1=pElem->FirstChildElement(); //pElem1=pElem1->FirstChildElement(); while(pElem_1) { CString str_1 = _T(""); CString element_1 = _T(""); DWORD str_Len_1 = 0; TCHAR * dstTCHAR_1 = NULL; // test.Format(L"%s", pElem->GetText()); char *psNode_1 = (char*)pElem_1->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL); dstTCHAR_1 = new TCHAR[str_Len + 1]; memset(dstTCHAR_1, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len); element_1.Format(L"%s",dstTCHAR_1); delete [] dstTCHAR_1; // CreateDate if(element_1.Find(_T("CreateDate"))!= -1) { TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text != NULL) { str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str1.Format((L"%s"),dstTch); str1 = ConvertUTC(str1, 9); // UTC 시간 적용 delete []dstTch; } } // Sender else if(element_1.Find(_T("Sender"))!= -1) { TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text != NULL) { str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str2.Format((L"%s"),dstTch); delete []dstTch; } else str2 = L"NULL"; } // Receivers else if(element_1.Find(_T("Receivers"))!= -1) { TiXmlElement* pElem_2 = pElem_1->FirstChildElement(); const char *text = pElem_2->GetText(); if(text != NULL) { TCHAR* dstTch = NULL; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str3.Format((L"%s"), dstTch); delete []dstTch; } else str3 = L"NULL"; } else if(element_1.Find(_T("MsgState"))!= -1){ TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str4.Format((L"%s"),dstTch); delete []dstTch; } // Encoded Content else if(element_1.Find(_T("EncodedContent"))!= -1) { const char *text = pElem_1->GetText(); if(text == NULL) break; string cipher(text); PBYTE buf_cipher = (PBYTE)malloc(cipher.size()+1); buf_cipher[cipher.size()] = 0x00; memcpy(buf_cipher, cipher.c_str(), cipher.size()); INT length = base64_decode((PCHAR)buf_cipher, buf_cipher, cipher.size()); wchar_t strUnicode[256] = {0,}; int nLen = MultiByteToWideChar(CP_UTF8, 0, (const char*)buf_cipher, strlen((const char*)buf_cipher), NULL, NULL); MultiByteToWideChar(CP_UTF8, 0, (const char*)buf_cipher, strlen((const char*)buf_cipher), strUnicode, nLen);// utf-8 to unicode //strUnicode 바꿔 저장 stMessageXml.createDate = str1; stMessageXml.sender = str2; stMessageXml.receivers = str3; stMessageXml.msgState = str4; stMessageXml.encodedContent = strUnicode; mMessageXml.insert(pair_MessageXml(stMessageXml.createDate, stMessageXml)); stMessageXml.createDate.Empty(); stMessageXml.msgState.Empty(); stMessageXml.sender.Empty(); stMessageXml.receivers.Empty(); stMessageXml.encodedContent.Empty(); } pElem_1 = pElem_1->NextSiblingElement(); } } pElem = pElem->NextSiblingElement(); } while(pElem2) { CString str1=_T(""); CString str2=_T(""); CString str3=_T(""); CString str4=_T(""); CString str5=_T(""); CString str6=_T(""); CString element=_T(""); DWORD str_Len = 0; TCHAR * dstTCHAR = NULL; char *psNode = (char*)pElem2->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL); dstTCHAR = new TCHAR[str_Len + 1]; memset(dstTCHAR, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len); element.Format(L"%s",dstTCHAR); delete [] dstTCHAR; if(element.Find(L"MMSStoreItem") != -1) { TiXmlElement* pElem_1=pElem2->FirstChildElement(); while(pElem_1) { CString str_1=_T(""); CString element_1=_T(""); DWORD str_Len_1 = 0; TCHAR * dstTCHAR_1 = NULL; char *psNode_1 = (char*)pElem_1->Value(); str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL); dstTCHAR_1 = new TCHAR[str_Len + 1]; memset(dstTCHAR_1, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len); element_1.Format(L"%s",dstTCHAR_1); delete [] dstTCHAR_1; if(element_1.Compare(_T("Folder")) == 0) { TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text != NULL) { str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str1.Format((L"%s"),dstTch); delete []dstTch; } } // Sender else if(element_1.Find(_T("Sender"))!= -1) { TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text != NULL) { str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str2.Format((L"%s"),dstTch); delete []dstTch; } else str2 = L"NULL"; } // Receivers else if(element_1.Find(_T("Receivers"))!= -1) { TiXmlElement* pElem_2 = pElem_1->FirstChildElement(); const char *text = pElem_2->GetText(); if(text != NULL) { TCHAR* dstTch = NULL; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str3.Format((L"%s"), dstTch); delete []dstTch; } else str3 = L"NULL"; } // CreateDate else if(element_1.Find(_T("CreateDate"))!= -1) { TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); if(text != NULL) { str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str5.Format((L"%s"),dstTch); str5 = ConvertUTC(str5, 9); // UTC 시간 적용 delete []dstTch; } } else if(element_1.Find(_T("MMSBody"))!= -1) { TCHAR* dstTch = NULL; const char *text = pElem_1->GetText(); std::string newString; if(text == NULL) break; str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL); dstTch = new TCHAR[str_Len + 1]; memset(dstTch, 0x00, str_Len * 2 + 2); MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len); str6.Format((L"%s"),dstTch); delete []dstTch; CT2CA pszConvertedAnsiString (str6); string tmp(pszConvertedAnsiString); for(int i = 0; i < tmp.length() - 0x0c*2; i +=2) { string byte = tmp.substr(i+0x0c*2,2); char chr = (char) (int)strtol(byte.c_str(), NULL, 16); newString.push_back(chr); } wchar_t strUnicode[20480] = {0,}; int nLen = MultiByteToWideChar(CP_UTF8, 0, (const char*)newString.c_str(), strlen((const char*)newString.c_str()), NULL, NULL); MultiByteToWideChar(CP_UTF8, 0, (const char*)newString.c_str(), strlen((const char*)newString.c_str()), strUnicode, nLen);// utf-8 to unicode //strUnicode 바꿔 저장 stMMSMessageXml.folder = str1; stMMSMessageXml.sender = str2; stMMSMessageXml.receivers = str3; stMMSMessageXml.createDate = str5; stMMSMessageXml.mMsbody = strUnicode; mMMSMessageXml.insert(pair_MMSMessageXml(stMMSMessageXml.folder, stMMSMessageXml)); stMMSMessageXml.folder.Empty(); stMMSMessageXml.sender.Empty(); stMMSMessageXml.receivers.Empty(); stMMSMessageXml.createDate.Empty(); stMMSMessageXml.mMsbody.Empty(); } pElem_1 = pElem_1->NextSiblingElement(); } } pElem2 = pElem2->NextSiblingElement(); } END_PROCESS: m_Document.Clear(); if(XMLData) delete XMLData; CreateWriteSMSMessageXmlCSVFile((CString)outputPath); CreateWriteMMSMessageXmlCSVFile((CString)outputPath); return 1; }
/////////////////////////////////////////////////////////////////////////////// // This function will parse the source file and create the token file CMainApp::Error_Codes CMainApp::TokGen() { Error_Codes ReturnErr = ERR_NOERROR; WriteCon(CONERR, "%s\r\n", CalcTab("", 79, '-')); // Open the iodll.dll using the first file name HANDLE hModule = RSOpenModule(m_strInExe, NULL); if ((int)hModule < 100) { // error or warning WriteCon(CONERR, "%s", CalcTab(m_strInExe, m_strInExe.GetLength()+5, ' ')); IoDllError((int)hModule); return ERR_FILE_NOTSUPP; } else { // before we do anything else we have to check how many languages we have in the file CString strLang; char szLang[8]; BOOL b_multi_lang = FALSE; USHORT usInputLang = MAKELANGID(m_usIPriLangId, m_usISubLangId); if((b_multi_lang = RSLanguages(hModule, strLang.GetBuffer(128))) && !IsFlag(INPUT_LANG)) { // this is a multiple language file but we don't have an input language specified // Fail, but warn the user that he has to set the input language to continue. strLang.ReleaseBuffer(); WriteCon(CONERR, "Multiple language file. Please specify an input language %s.\r\n", strLang); goto exit; } // Convert the language in to the hex value sprintf(szLang,"0x%3.3X", usInputLang); // Check if the input language that we got is a valid one if(IsFlag(INPUT_LANG) && strLang.Find(szLang)==-1) { WriteCon(CONERR, "The language %s in not a valid language for this file.\r\n", szLang); WriteCon(CONERR, "Valid languages are: %s.\r\n", strLang); goto exit; } // Check if the user is extracting the neutral language if(!usInputLang) usInputLang = 0xFFFF; // Open the output file CStdioFile fileOut; if(!fileOut.Open(m_strTgtTok, CFile::modeCreate | CFile::modeReadWrite)) { WriteCon(CONERR, "Cannot create file: %s\r\n", CalcTab(m_strTgtTok, m_strTgtTok.GetLength()+5, ' ')); return ERR_FILE_CREATE; } CString strBmpDir = ""; CString strFileName = m_strInExe; int pos = m_strInExe.ReverseFind('\\'); if(pos!=-1) { strFileName = m_strInExe.Right(m_strInExe.GetLength()-pos-1); } else if((pos = m_strInExe.ReverseFind(':'))!=-1) { strFileName = m_strInExe.Right(m_strInExe.GetLength()-pos-1); } pos = m_strTgtTok.ReverseFind('\\'); if(pos!=-1) { strBmpDir = m_strTgtTok.Left(pos+1); } else if((pos = m_strTgtTok.ReverseFind(':'))!=-1) { strBmpDir = m_strTgtTok.Left(pos+1); } // inform the user ... WriteCon(CONOUT, "Processing\t"); WriteCon(CONBOTH, "%s", CalcTab(strFileName, strFileName.GetLength()+5, ' ')); LPCSTR lpszType = 0L; LPCSTR lpszRes = 0L; DWORD dwLang = 0L; DWORD dwItem = 0L; DWORD dwItemID = 0L; LPRESITEM lpResItem = NULL; CString strToken; CString strResName; CString strCaption; WORD wFlag; BOOL bSkip = FALSE; BOOL bSkipEmpty = FALSE; BOOL bSkipLang = FALSE; WORD wCount = 0; WORD wMsgCount = 0; int iPos = 1; int iBmpIdCount = 0; BOOL bVersionStampOnly = TRUE; while ((lpszType = RSEnumResType(hModule, lpszType))) { // Check if is one of the type we care about if(HIWORD(lpszType)==0) switch(LOWORD(lpszType)) { case 2: case 3: if(theApp.IsFlag(CMainApp::BITMAPS)) bSkip = FALSE; else bSkip = TRUE; break; case 4: case 5: case 6: case 9: case 10: case 11: bVersionStampOnly = FALSE; case 16: bSkip = FALSE; break; default: bSkip = TRUE; } lpszRes = 0L; dwLang = 0L; dwItem = 0L; while ((!bSkip) && (lpszRes = RSEnumResId(hModule, lpszType, lpszRes))) { while ((dwLang = RSEnumResLang(hModule, lpszType, lpszRes, dwLang))) { // Check if we have to skip this language if(b_multi_lang && (LOWORD(dwLang)!=usInputLang)) bSkipLang = TRUE; else bSkipLang = FALSE; while ((!bSkipLang) && (dwItem = RSEnumResItemId(hModule, lpszType, lpszRes, dwLang, dwItem))) { // Now Get the Data DWORD dwImageSize = RSGetResItemData( hModule, lpszType, lpszRes, dwLang, dwItem, m_pBuf, MAX_BUF_SIZE ); lpResItem = (LPRESITEM)m_pBuf; if((wCount++ % 50)==0) WriteCon(CONOUT, "."); // Check if we want or not empty strings switch(lpResItem->dwTypeID) { case 4: case 5: case 16: bSkipEmpty = TRUE; break; default: bSkipEmpty = FALSE; break; } // Version stamp use class name as res id if(lpResItem->lpszResID) strResName = lpResItem->lpszResID; else strResName = ""; dwItemID = lpResItem->dwItemID; // Add font info for dialogs if((theApp.IsFlag(CMainApp::FONTS) && (lpResItem->dwTypeID==5) && (dwItemID==0))) { // Add font information sprintf(strToken.GetBuffer(MAX_STR_SIZE), TEXT("[[%u|%u|%u|%u|%u|\"%s\"]]=%s:%hd\n"), lpResItem->dwTypeID, lpResItem->dwResID, dwItemID, ISDLGFONTNAME | ISDLGFONTSIZE, ST_TRANSLATED, strResName.GetBuffer(0), Format(lpResItem->lpszFaceName), lpResItem->wPointSize); fileOut.WriteString(strToken); } strCaption = lpResItem->lpszCaption; // Set the flag wFlag = 0; if(!(bSkipEmpty && strCaption.IsEmpty())) { switch(lpResItem->dwTypeID) { case 2: case 3: { // create the BMP name CString strBmpName; if(lpResItem->dwTypeID==2) if(lpResItem->dwResID) strBmpName = CreateName(strFileName, ".bmp", lpResItem->dwResID); else strBmpName = CreateName(strFileName, ".bmp", lpResItem->lpszResID); else if(lpResItem->dwResID) strBmpName = CreateName(strFileName, ".ico", lpResItem->dwResID); else strBmpName = CreateName(strFileName, ".ico", lpResItem->lpszResID); // Get the image from the file DWORD dwBufSize = RSGetResImage( hModule, lpszType, lpszRes, dwLang, NULL, 0 ); BYTE * pBuf = (BYTE*)(new BYTE[dwBufSize]); if(pBuf==NULL) { WriteCon(CONERR, "Warning: Failed to allocate buffer for image! (%d, %d, %s, Size: %d)\r\n", lpResItem->dwTypeID, lpResItem->dwResID, lpResItem->lpszResID, dwBufSize); break; } dwBufSize = RSGetResImage( hModule, lpszType, lpszRes, dwLang, pBuf, dwBufSize ); // write the data in to a file CFile BmpFile; if(!BmpFile.Open(strBmpDir+strBmpName, CFile::modeCreate | CFile::modeWrite)) { WriteCon(CONERR, "Cannot create file: %s\r\n", CalcTab(strBmpDir+strBmpName, strBmpName.GetLength()+strBmpDir.GetLength()+5, ' ')); delete pBuf; break; } switch(lpResItem->dwTypeID) { case 2: { BITMAPFILEHEADER bmpFileHeader; BITMAPINFO * pbmpInfo = (BITMAPINFO *)pBuf; DWORD dwNumColor = 0; if(pbmpInfo->bmiHeader.biBitCount!=24) dwNumColor = ( 1L << pbmpInfo->bmiHeader.biBitCount); bmpFileHeader.bfType = 0x4d42; bmpFileHeader.bfSize = (dwBufSize+sizeof(BITMAPFILEHEADER))/4; bmpFileHeader.bfReserved1 = 0; bmpFileHeader.bfReserved2 = 0; bmpFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + pbmpInfo->bmiHeader.biSize + dwNumColor*sizeof(RGBQUAD); BmpFile.Write(&bmpFileHeader, sizeof(BITMAPFILEHEADER)); } break; case 3: { ICONHEADER icoHeader; BITMAPINFOHEADER * pbmpInfoH = (BITMAPINFOHEADER*)pBuf; icoHeader.idReserved = 0; icoHeader.idType = 1; icoHeader.idCount = 1; icoHeader.bWidth = LOBYTE(pbmpInfoH->biWidth); icoHeader.bHeight = LOBYTE(pbmpInfoH->biWidth); icoHeader.bColorCount = 16; icoHeader.bReserved = 0; icoHeader.wPlanes = 0; icoHeader.wBitCount = 0; icoHeader.dwBytesInRes = dwBufSize; icoHeader.dwImageOffset = sizeof(ICONHEADER); BmpFile.Write(&icoHeader, sizeof(ICONHEADER)); } break; default: break; } BmpFile.Write(pBuf, dwBufSize); BmpFile.Close(); delete pBuf; strCaption = strBmpName; } break; case 4: if(lpResItem->dwFlags & MF_POPUP) { wFlag = ISPOPUP; // check if this popup has a valid ID if (LOWORD(dwItemID)==0xffff) wFlag |= OLD_POPUP_ID; dwItemID = (LOWORD(dwItemID)==0xffff ? HIWORD(dwItemID) : dwItemID); } break; case 5: if(dwItemID==0) { wFlag = ISCAP; } // check if this is a duplicated id if (LOWORD(dwItemID)==0xffff) wFlag |= ISDUP; dwItemID = (LOWORD(dwItemID)==0xffff ? HIWORD(dwItemID) : dwItemID); break; case 9: { CAccel accel(lpResItem->dwFlags, lpResItem->dwStyle); strCaption = accel.GetText(); // check if this is a duplicated ID if(HIWORD(dwItemID)) { wFlag |= ISDUP; } } break; case 11: dwItemID = LOWORD(dwItemID); break; case 16: strResName = lpResItem->lpszClassName; break; default: break; } // Create the token file if(lpResItem->dwTypeID==11 && theApp.IsFlag(CMainApp::SPLIT)) { // Search for the \r\n and replace them while((iPos = strCaption.Find("\r\n"))!=-1) { sprintf(strToken.GetBuffer(MAX_STR_SIZE), TEXT("[[%u|%u|%u|%u|%u|\"%s\"]]=%s\\r\\n\n"), lpResItem->dwTypeID, lpResItem->dwResID, dwItemID, wFlag | wMsgCount++, ST_TRANSLATED, strResName.GetBuffer(0), Format(strCaption.Left(iPos))); strCaption = strCaption.Right(strCaption.GetLength()-2-iPos); fileOut.WriteString(strToken); } wMsgCount = 0; } else { sprintf(strToken.GetBuffer(MAX_STR_SIZE), TEXT("[[%u|%u|%u|%u|%u|\"%s\"]]=%s\n"), lpResItem->dwTypeID, lpResItem->dwResID, dwItemID, /*(LOWORD(dwItemID)==0xffff ? HIWORD(dwItemID) : dwItemID),*/ wFlag, ST_TRANSLATED, strResName.GetBuffer(0), Format(strCaption)); fileOut.WriteString(strToken); } // If this is a dialog box add the coordinates if(lpResItem->dwTypeID==5) { sprintf(strToken.GetBuffer(MAX_STR_SIZE), TEXT("[[%u|%u|%u|%u|%u|\"%s\"]]=%hu %hu %hu %hu\n"), lpResItem->dwTypeID, lpResItem->dwResID, (LOWORD(dwItemID)==0xffff ? HIWORD(dwItemID) : dwItemID), wFlag | ISCOR, ST_TRANSLATED, strResName.GetBuffer(0), lpResItem->wX, lpResItem->wY, lpResItem->wcX, lpResItem->wcY); fileOut.WriteString(strToken); } } else { // If this is a dialog box add the coordinates if(lpResItem->dwTypeID==5) { sprintf(strToken.GetBuffer(MAX_STR_SIZE), TEXT("[[%u|%u|%u|%u|%u|\"%s\"]]=%hu %hu %hu %hu\n"), lpResItem->dwTypeID, lpResItem->dwResID, (LOWORD(dwItemID)==0xffff ? HIWORD(dwItemID) : dwItemID), wFlag | ISCOR, ST_TRANSLATED, strResName.GetBuffer(0), lpResItem->wX, lpResItem->wY, lpResItem->wcX, lpResItem->wcY); fileOut.WriteString(strToken); } } } // end while } } } fileOut.Close(); // Check the size of the new file and remove it if empty... CFileStatus fstat; if(CFile::GetStatus(m_strTgtTok, fstat)) if(fstat.m_size==0) CFile::Remove(m_strTgtTok); WriteCon(CONBOTH, " %hu Items\r\n", wCount); if(bVersionStampOnly) { ReturnErr = ERR_FILE_VERSTAMPONLY; WriteCon(CONWRN, "%s : Version Stamping only!\r\n", strFileName); } } exit: RSCloseModule(hModule); return ReturnErr; }
int CModel::Read (char *filename, short nModel, int bFlipV, int bCustom) { if (m_nModel >= 0) return 0; CFile cf; char fileId [4]; int i, nLength, nFrames, nSubModels, bTimed = 0; bLogOOF = (fErr != NULL) && FindArg ("-printoof"); nIndent = 0; OOF_PrintLog ("\nreading %s/%s\n", gameFolders.szModelDir [bCustom], filename); if (!(*filename && cf.Open (filename, gameFolders.szModelDir [bCustom], "rb", 0))) { OOF_PrintLog (" file not found"); return 0; } if (!cf.Read (fileId, sizeof (fileId), 1)) { OOF_PrintLog (" invalid file id\n"); cf.Close (); return 0; } if (strncmp (fileId, "PSPO", 4)) { OOF_PrintLog (" invalid file id\n"); cf.Close (); return 0; } Init (); m_nModel = nModel; m_bCustom = bCustom; m_nVersion = OOF_ReadInt (cf, "nVersion"); if (m_nVersion >= 2100) m_nFlags |= OOF_PMF_LIGHTMAP_RES; if (m_nVersion >= 22) { bTimed = 1; m_nFlags |= OOF_PMF_TIMED; m_frameInfo.m_nFirstFrame = 0; m_frameInfo.m_nLastFrame = 0; } nSubModels = 0; while (!cf.EoF ()) { char chunkID [4]; if (!cf.Read (chunkID, sizeof (chunkID), 1)) { cf.Close (); return 0; } OOF_PrintLog (" chunkID = '%c%c%c%c'\n", chunkID [0], chunkID [1], chunkID [2], chunkID [3]); nLength = OOF_ReadInt (cf, "nLength"); switch (ListType (chunkID)) { case 0: if (!ReadTextures (cf)) { Destroy (); return 0; } break; case 1: if (!ReadInfo (cf)) { Destroy (); return 0; } break; case 2: if (!m_subModels [nSubModels].Read (cf, this, bFlipV)) { Destroy (); return 0; } nSubModels++; break; case 3: if (!m_gunPoints.Read (cf, m_nVersion >= 1908, MAX_GUNS)) { Destroy (); return 0; } break; case 4: if (!m_specialPoints.Read (cf)) { Destroy (); return 0; } break; case 5: if (!m_attachPoints.Read (cf)) { Destroy (); return 0; } break; case 6: nFrames = m_frameInfo.m_nFrames; if (!bTimed) m_frameInfo.m_nFrames = OOF_ReadInt (cf, "nFrames"); for (i = 0; i < m_nSubModels; i++) if (!m_subModels [i].m_posAnim.Read (cf, this, bTimed)) { Destroy (); return 0; } if (m_frameInfo.m_nFrames < nFrames) m_frameInfo.m_nFrames = nFrames; break; case 7: case 8: nFrames = m_frameInfo.m_nFrames; if (!bTimed) m_frameInfo.m_nFrames = OOF_ReadInt (cf, "nFrames"); for (i = 0; i < m_nSubModels; i++) if (!m_subModels [i].m_rotAnim.Read (cf, this, bTimed)) { Destroy (); return 0; } if (m_frameInfo.m_nFrames < nFrames) m_frameInfo.m_nFrames = nFrames; break; case 9: if (!m_armament.Read (cf)) { Destroy (); return 0; } break; case 10: if (!m_attachPoints.ReadNormals (cf)) { Destroy (); return 0; } break; default: cf.Seek (nLength, SEEK_CUR); break; } } cf.Close (); ConfigureSubModels (); BuildAnimMatrices (); AssignChildren (); LinkBatteries (); BuildPosTickRemapList (); BuildRotTickRemapList (); gameData.models.bHaveHiresModel [this - gameData.models.oofModels [bCustom != 0].Buffer ()] = 1; return 1; }
// 生成测线仪器排列文件 void CFraseSPSToXML::GenLineInitTXT(CString strPath) { CFile file; unsigned int uiMax = OnCalMax(); unsigned int uiLAULNum = 0; // 电源站个数 unsigned int uiLineNum = m_vecLine.size(); unsigned int uiCharSize = 0; unsigned int uiPosition = 0; if (uiMax == 0) { return; } if (uiLineNum == 0) { return; } if (uiMax < (m_uiLAUXNum + m_uiBlastMachineNum + m_uiLAUXNum)) { uiMax = m_uiLAUXNum + m_uiBlastMachineNum + m_uiLAUXNum; } uiLAULNum = (uiMax / 2) / (m_uiIntervalLAUL + 1) + (uiMax - uiMax / 2) / (m_uiIntervalLAUL + 1); unsigned int uiLineCount = (uiLineNum + 1) * 2 - 1; unsigned int uiColumnCount = (m_uiLAUXNum + uiLAULNum + uiMax) * 2 - 1 + 2; uiCharSize = uiLineCount * uiColumnCount; unsigned char * pWriteChar = new unsigned char [uiCharSize]; unsigned char ucInit = ' '; memset(pWriteChar, ucInit, uiCharSize); // 回车换行赋值 for (unsigned int i=0; i<uiLineCount; i++) { uiPosition = (i + 1) * uiColumnCount - 2; pWriteChar[uiPosition] = '\r'; uiPosition = (i + 1) * uiColumnCount - 1; pWriteChar[uiPosition] = '\n'; } // 交叉站及交叉线赋值 for (unsigned int i=0; i<uiLineCount; i++) { uiPosition = (uiMax - uiMax / 2 + (uiMax - uiMax / 2) / (m_uiIntervalLAUL + 1)) * 2 + i * uiColumnCount; if (i == 0) { pWriteChar[uiPosition] = LAUX_LOGO; } else if (i % 2 == 1) { pWriteChar[uiPosition] = LAUXLINE_LOGO; } else { pWriteChar[uiPosition] = LAU_LOGO; } } // 左侧爆炸机赋值 uiPosition = (uiMax - uiMax / 2 + (uiMax - uiMax / 2) / (m_uiIntervalLAUL + 1)) * 2; for (unsigned int i=0; i<m_uiBlastMachineNum; i++) { pWriteChar[uiPosition - i * 2 - 1] = LINE_LOGO; pWriteChar[uiPosition - i * 2 - 2] = BLAST_LOGO; } // 右侧辅助道赋值 uiPosition = (uiMax - uiMax / 2 + (uiMax - uiMax / 2) / (m_uiIntervalLAUL + 1)) * 2; for (unsigned int i=0; i<m_uiAuxNum; i++) { pWriteChar[uiPosition + i * 2 + 1] = LINE_LOGO; pWriteChar[uiPosition + i * 2 + 2] = AUX_LOGO; } unsigned int uiFDUNumLeft = 0; // 左侧采集站个数 unsigned int uiFDUNumRight = 0; // 右侧采集站个数 // 采集站及电源站赋值 for (unsigned int i=2; i<uiLineCount; i++) { if (i % 2 == 0) { uiPosition = (uiMax - uiMax / 2 + (uiMax - uiMax / 2) / (m_uiIntervalLAUL + 1)) * 2 + i * uiColumnCount; uiFDUNumRight = m_vecLine[(i - 2) / 2] / 2; uiFDUNumLeft = m_vecLine[(i - 2) / 2] - uiFDUNumRight; // 左侧采集站及电源站赋值 for (unsigned int j=0; j<(uiFDUNumLeft + uiFDUNumLeft / (m_uiIntervalLAUL + 1)); j++) { pWriteChar[uiPosition - j * 2 - 1] = LINE_LOGO; if (((j + 1) % (m_uiIntervalLAUL + 1) == 0) && (j != 0)) { pWriteChar[uiPosition - j * 2 - 2] = LAUL_LOGO; } else { pWriteChar[uiPosition - j * 2 - 2] = FDU_LOGO; } } // 右侧采集站及电源站赋值 for (unsigned int j=0; j<(uiFDUNumRight + uiFDUNumRight / (m_uiIntervalLAUL + 1)); j++) { pWriteChar[uiPosition + j * 2 + 1] = LINE_LOGO; if (((j + 1) % (m_uiIntervalLAUL + 1) == 0) && (j != 0)) { pWriteChar[uiPosition + j * 2 + 2] = LAUL_LOGO; } else { pWriteChar[uiPosition + j * 2 + 2] = FDU_LOGO; } } } } if (FALSE == file.Open(strPath, CFile::modeCreate|CFile::modeWrite)) { AfxMessageBox(_T("Create LineInit file error, Please check it again!")); return; } // 写文件内容 file.Write(pWriteChar, uiCharSize); file.Close(); delete[] pWriteChar; }
// 读取PAL文件转换为RGB并显示 void CRGB2YUVView::OnReadPAL() { // TODO: Add your command handler code here CDC *pDC = GetDC(); CRect rect; CBrush brush(RGB(128,128,128)); GetClientRect(&rect); pDC->FillRect(&rect, &brush); // PAL 720x576 : 中国的电视标准为PAL制 int CurrentXRes = 720; int CurrentYRes = 576; int size = CurrentXRes * CurrentYRes; // 分配内存 byte *Video_Field0 = (byte*)malloc(CurrentXRes*CurrentYRes); byte *Video_Field1 = (byte*)malloc(CurrentXRes*CurrentYRes); // 保存内存指针 byte *Video_Field0_ = Video_Field0; byte *Video_Field1_ = Video_Field1; // 初始化内存 ZeroMemory(Video_Field0, CurrentXRes*CurrentYRes); ZeroMemory(Video_Field1, CurrentXRes*CurrentYRes); byte yuv_y0, yuv_u0, yuv_v0; // yuv_v1; // {y0, u0, v0, v1}; byte r, g, b; byte bufRGB[3]; // 临时保存{R,G,B} byte bufYUV[3]; // 临时保存{Y,U,V} // 初始化数组空间 memset(bufRGB,0, sizeof(byte)*3); memset(bufYUV,0, sizeof(byte)*3); char strFileName[MAX_PATH]="720bmp.pal"; // 分配图片像素内存 RGBTRIPLE *rgb; rgb = new RGBTRIPLE[CurrentXRes*CurrentYRes]; memset(rgb,0, sizeof(RGBTRIPLE)*CurrentXRes*CurrentYRes); // 初始化内存空间 CFile* f; f = new CFile(); f->Open(strFileName, CFile::modeRead); f->SeekToBegin(); f->Read(Video_Field0, CurrentXRes*CurrentYRes); f->Read(Video_Field1, CurrentXRes*CurrentYRes); // 上场 (1,3,5,7...行) for ( int i = CurrentYRes-1; i>=0; i--) { for ( int j = 0; j<CurrentXRes; j++) { if(!(i%2)==0) { // UYVY标准 [U0 Y0 V0 Y1] [U1 Y2 V1 Y3] [U2 Y4 V2 Y5] 每像素点两个字节,[内]为四个字节 if ((j%2)==0) { yuv_u0 = *Video_Field0; Video_Field0++; } else { yuv_v0 = *Video_Field0; Video_Field0++; } yuv_y0 = *Video_Field0; Video_Field0++; bufYUV[0] = yuv_y0; // Y bufYUV[1] = yuv_u0; // U bufYUV[2] = yuv_v0; // V // RGB转换为YUV YUV2RGB(bufRGB,bufYUV); r = bufRGB[0]; // y g = bufRGB[1]; // u b = bufRGB[2]; // v if (r>255) r=255; if (r<0) r=0; if (g>255) g=255; if (g<0) g=0; if (b>255) b=255; if (b<0) b=0; for (int k=0; k<1000; k++) ; //延时 // 视图中显示 pDC->SetPixel(j, CurrentYRes-1-i, RGB(r, g, b)); }// end if i%2 } } // 下场 (2,4,6,8...行) for ( int i_ = CurrentYRes-1; i_>=0; i_--) { for ( int j_ = 0; j_<CurrentXRes; j_++) { if((i_%2)==0) { // UYVY标准 [U0 Y0 V0 Y1] [U1 Y2 V1 Y3] [U2 Y4 V2 Y5] 每像素点两个字节,[内]为四个字节 if ((j_%2)==0) { yuv_u0 = *Video_Field1; Video_Field1++; } else { yuv_v0 = *Video_Field1; Video_Field1++; } yuv_y0 = *Video_Field1; Video_Field1++; bufYUV[0] = yuv_y0; // Y bufYUV[1] = yuv_u0; // U bufYUV[2] = yuv_v0; // V // RGB转换为YUV YUV2RGB(bufRGB,bufYUV); r = bufRGB[0]; // y g = bufRGB[1]; // u b = bufRGB[2]; // v if (r>255) r=255; if (r<0) r=0; if (g>255) g=255; if (g<0) g=0; if (b>255) b=255; if (b<0) b=0; for (int k=0; k<1000; k++) ; //延时 // 视图中显示 pDC->SetPixel(j_, CurrentYRes-1-i_, RGB(r, g, b)); } } } // 提示完成 char buffer[80]; sprintf(buffer,"完成读取PAL文件:%s ", strFileName); MessageBox(buffer, "提示信息", MB_OK | MB_ICONINFORMATION); // 关闭PAL电视场文件 f->Close(); // WriteYUV(Video_Field0_, Video_Field1_, size); // 释放内存 free( Video_Field0_ ); free( Video_Field1_ ); delete f; delete rgb; }
void TabDoc::DecodeHTML(const char* filename, int scheme) { // Open the file CFile htmlFile; if (htmlFile.Open(filename,CFile::modeRead) == 0) return; // Read it into memory CString htmlText; int len = (int)htmlFile.GetLength(); htmlFile.Read(htmlText.GetBuffer(len),len); htmlText.ReleaseBuffer(len); // Convert from UTF-8 to Unicode CStringW html = TextFormat::UTF8ToUnicode(htmlText); // Get the body text int body1 = html.Find(L"<body"); if (body1 == -1) return; body1 = html.Find(L">",body1); if (body1 == -1) return; int body2 = html.Find(L"</body>"); if (body2 <= body1) return; CStringW bodyHtml = html.Mid(body1+1,body2-body1-1); // Create a DocText instance for this file DocText* mainDocText = new DocText(); mainDocText->file = filename; mainDocText->colourScheme = scheme; m_docTexts.Add(mainDocText); // Reserve space for the main text len = bodyHtml.GetLength(); mainDocText->body.Preallocate(len); // Scan the text, removing markup DocText* docText = mainDocText; bool ignore = false; bool white = false; const wchar_t* p1 = bodyHtml; const wchar_t* p2 = p1+len; while (p1 < p2) { // Look for a markup element if ((*p1 == L'<') && (iswalpha(*(p1+1)) || (*(p1+1) == L'/'))) { // Check for a closing markup element bool closing = false; if (*(p1+1) == L'/') { closing = true; p1++; } // Scan for a known markup element bool found = false; int i = 0; while (!found && (i < sizeof tags / sizeof tags[0])) { if (wcsncmp(p1+1,tags[i].name,tags[i].len) == 0) found = true; if (!found) i++; } ASSERT(found); // Remove the markup if (found && tags[i].remove) { ASSERT(!closing); // Remove everything until the closing element CStringW search; search.Format(L"</%s>",tags[i].name); p1 = wcsstr(p1,search); if (p1 != NULL) p1 += search.GetLength()-1; else p1 = p2; } else { // Remove just the element while ((p1 < p2) && (*p1 != L'>')) p1++; } ASSERT(*p1 == L'>'); // Add a carriage return for appropriate markup if (found && !closing && tags[i].cr && !ignore) docText->AddToBody(L'\n'); white = false; } else if ((*p1 == L'<') && (*(p1+1) == L'!')) { // Extract metadata from comments wchar_t meta1[256], meta2[256]; if (swscanf(p1,L"<!-- SEARCH TITLE \"%[^\"]",meta1) == 1) docText->title = meta1; else if (swscanf(p1,L"<!-- SEARCH SECTION \"%[^\"]",meta1) == 1) docText->section = meta1; else if (swscanf(p1,L"<!-- SEARCH SORT \"%[^\"]",meta1) == 1) docText->sort = meta1; else if (swscanf(p1,L"<!-- START EXAMPLE \"%[^\"]\" \"%[^\"]",meta1,meta2) == 2) { docText = new DocText(); docText->file = mainDocText->file + "#" + CStringA(meta2); docText->colourScheme = mainDocText->colourScheme; docText->title = "Example " + CStringA(meta1); docText->section = mainDocText->section; docText->sort = mainDocText->sort; docText->body.Preallocate(len/2); m_docTexts.Add(docText); } else if (wcsncmp(p1,L"<!-- END EXAMPLE -->",20) == 0) docText = mainDocText; else if (wcsncmp(p1,L"<!-- START IGNORE ",18) == 0) ignore = true; else if (wcsncmp(p1,L"<!-- END IGNORE -->",19) == 0) ignore = false; p1 = wcsstr(p1,L"-->"); if (p1 != NULL) p1 += 2; else p1 = p2; } else if (*p1 == L'&') { // Scan for a known literal bool found = false; int i = 0; while (!found && (i < sizeof literals / sizeof literals[0])) { if (wcsncmp(p1+1,literals[i].name,literals[i].len) == 0) found = true; if (!found) i++; } // Replace the literal if (found) { if (!ignore) docText->AddToBody(literals[i].replace); p1 += literals[i].len; } else { ASSERT(FALSE); if (!ignore) docText->AddToBody(*p1); } white = false; } else if (iswspace(*p1)) { if (!white && !ignore) docText->AddToBody(L' '); white = true; } else { if (!ignore) docText->AddToBody(*p1); white = false; } p1++; } /* CString bodyA(docText->body); AfxMessageBox(bodyA); */ }
// 隔行显示BMP void CRGB2YUVView::OnReadBmp() { // TODO: Add your command handler code here CDC *pDC = GetDC(); CRect rect; CBrush brush(RGB(128,128,128)); GetClientRect(&rect); pDC->FillRect(&rect, &brush); BITMAPFILEHEADER bmfh; BITMAPINFOHEADER bmih; char strFileName[MAX_PATH]="720bmp.bmp"; CFile* f; f = new CFile(); f->Open(strFileName, CFile::modeRead); f->SeekToBegin(); f->Read(&bmfh, sizeof(bmfh)); f->Read(&bmih, sizeof(bmih)); // 分配图片像素内存 RGBTRIPLE *rgb; rgb = new RGBTRIPLE[bmih.biWidth*bmih.biHeight]; f->SeekToBegin(); f->Seek(54,CFile::begin); // BMP 54个字节之后的是像素数据 f->Read(rgb, bmih.biWidth * bmih.biHeight * 3); // 这里只读24位RGB(r,g,b)图像 // 显示上场 (奇数行组成的奇数场) for (int i = 0; i<bmih.biHeight; i++) { for (int j = 0; j<bmih.biWidth; j++) { if(!(i%2)) pDC->SetPixel(j, bmih.biHeight-i, RGB(rgb[i*bmih.biWidth+j].rgbtRed,rgb[i*bmih.biWidth+j].rgbtGreen,rgb[i*bmih.biWidth+j].rgbtBlue)); for (int k=0; k<1000; k++) ; //延时 } } Sleep(500); // 显示下场 (偶数行组成的偶数场) for (int i_ = 0; i_<bmih.biHeight; i_++) { for (int j_ = 0; j_<bmih.biWidth; j_++) { if(i_%2) pDC->SetPixel(j_, bmih.biHeight-i_, RGB(rgb[i_*bmih.biWidth+j_].rgbtRed,rgb[i_*bmih.biWidth+j_].rgbtGreen,rgb[i_*bmih.biWidth+j_].rgbtBlue)); for (int k=0; k<1000; k++) ; //延时 } } // 显示24位BMP信息 LONG dwWidth = bmih.biWidth; LONG dwHeight = bmih.biHeight; WORD wBitCount = bmih.biBitCount; char buffer[80]; sprintf(buffer,"图像宽为:%ld 高为:%ld 像数位数:%d", dwWidth, dwHeight, wBitCount); MessageBox(buffer, "每个像素的位数", MB_OK | MB_ICONINFORMATION); f->Close(); delete f; delete rgb; }
// This *looks* like a copy function, therefor the name "Cache" is misleading bool CFile::Cache(const CStdString& strFileName, const CStdString& strDest, XFILE::IFileCallback* pCallback, void* pContext) { CFile file; if (strFileName.empty() || strDest.empty()) return false; // special case for zips - ignore caching CURL url(strFileName); if (URIUtils::IsInZIP(strFileName) || URIUtils::IsInAPK(strFileName)) url.SetOptions("?cache=no"); if (file.Open(url.Get(), READ_TRUNCATED)) { CFile newFile; if (URIUtils::IsHD(strDest)) // create possible missing dirs { vector<CStdString> tokens; CStdString strDirectory; URIUtils::GetDirectory(strDest,strDirectory); URIUtils::RemoveSlashAtEnd(strDirectory); // for the test below if (!(strDirectory.size() == 2 && strDirectory[1] == ':')) { CURL url(strDirectory); CStdString pathsep; #ifndef TARGET_POSIX pathsep = "\\"; #else pathsep = "/"; #endif CUtil::Tokenize(url.GetFileName(),tokens,pathsep.c_str()); CStdString strCurrPath; // Handle special if (!url.GetProtocol().IsEmpty()) { pathsep = "/"; strCurrPath += url.GetProtocol() + "://"; } // If the directory has a / at the beginning, don't forget it else if (strDirectory[0] == pathsep[0]) strCurrPath += pathsep; for (vector<CStdString>::iterator iter=tokens.begin();iter!=tokens.end();++iter) { strCurrPath += *iter+pathsep; CDirectory::Create(strCurrPath); } } } if (CFile::Exists(strDest)) CFile::Delete(strDest); if (!newFile.OpenForWrite(strDest, true)) // overwrite always { file.Close(); return false; } int iBufferSize = 128 * 1024; CAutoBuffer buffer(iBufferSize); int iRead, iWrite; UINT64 llFileSize = file.GetLength(); UINT64 llPos = 0; CStopWatch timer; timer.StartZero(); float start = 0.0f; while (true) { g_application.ResetScreenSaver(); iRead = file.Read(buffer.get(), iBufferSize); if (iRead == 0) break; else if (iRead < 0) { CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, strFileName.c_str()); llFileSize = (uint64_t)-1; break; } /* write data and make sure we managed to write it all */ iWrite = 0; while(iWrite < iRead) { int iWrite2 = newFile.Write(buffer.get()+iWrite, iRead-iWrite); if(iWrite2 <=0) break; iWrite+=iWrite2; } if (iWrite != iRead) { CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, strDest.c_str()); llFileSize = (uint64_t)-1; break; } llPos += iRead; // calculate the current and average speeds float end = timer.GetElapsedSeconds(); if (pCallback && end - start > 0.5 && end) { start = end; float averageSpeed = llPos / end; int ipercent = 0; if(llFileSize) ipercent = 100 * llPos / llFileSize; if(!pCallback->OnFileCallback(pContext, ipercent, averageSpeed)) { CLog::Log(LOGERROR, "%s - User aborted copy", __FUNCTION__); llFileSize = (uint64_t)-1; break; } } } /* close both files */ newFile.Close(); file.Close(); /* verify that we managed to completed the file */ if (llFileSize && llPos != llFileSize) { CFile::Delete(strDest); return false; } return true; } return false; }
//http底层提交 bool CHttp::put(CString inbuff,CString *outbuff,CString type) { chunked=FALSE; char *len=new char[15]; char *content; int nrecv=0; if (MySocket==INVALID_SOCKET) return FALSE; if (m_bConnect==FALSE) return FALSE; if (type.Compare("img")!=0) *outbuff=""; int retval=::send(MySocket,(LPCTSTR)inbuff,inbuff.GetLength(),0); if( SOCKET_ERROR== retval ) return FALSE; char *urls=new char[1024*1024*2]; ZeroMemory(urls,1024*1024*2); //urls存储总下载源码 char *buffer=new char[1024]; WSAEVENT rwE = ::WSACreateEvent(); WSAEventSelect(MySocket, rwE, FD_READ|FD_CLOSE|FD_WRITE); while(1) { int ret=::WSAWaitForMultipleEvents(1, &rwE, FALSE,dwTimeOut, FALSE); WSANETWORKEVENTS event1; ::WSAEnumNetworkEvents(MySocket, rwE, &event1); if(event1.lNetworkEvents & FD_READ) { ZeroMemory(buffer,1024); retval= recv(MySocket ,buffer,1023,0); if (retval>0) { memcpy(urls+nrecv,buffer,retval); nrecv+=retval; } } else if(event1.lNetworkEvents & FD_OOB_BIT) { ZeroMemory(buffer,1024); retval= recv(MySocket ,buffer,1023,0); if (retval>0) { memcpy(urls+nrecv,buffer,retval); nrecv+=retval; } } else if(event1.lNetworkEvents & FD_CLOSE) { break; } else { break; } if (strstr(urls,"Transfer-Encoding: chunked")!=NULL) { chunked=TRUE; } else if(strstr(urls,"Content-Length")!=NULL) { strncpy(len,strstr(urls,"Content-Length")+16,10); char *end; end=strstr(len,"\r\n"); int nlen=end-len; len[nlen]='\0'; m_nContent=atoi(len); if (m_nContent>1024*1024*2) { *outbuff=""; goto label2; } content=strstr(urls,"\r\n\r\n")+4; int nheader=content-urls; if (nrecv-nheader==m_nContent) break; } if(chunked==TRUE ) { if(strstr(urls,"0\r\n\r\n")>0) break; } } //while end if (type.Compare("img")==0) { CFile file; file.Open(outbuff->GetString(),CFile::modeCreate|CFile::modeReadWrite| CFile::typeBinary); file.SeekToEnd(); file.Write(content,m_nContent); file.Close(); } *outbuff+=urls; BulidCookie(*outbuff); label2: WSACloseEvent(rwE); delete [] urls; delete [] buffer; delete [] len; return TRUE; }
void config_dialog::OnButSave() { // TODO: この位置にコントロール通知ハンドラ用のコードを追加してください static char filter[] = "equalizer file (*.eq)\0*.eq\0All files (*.*)\0*.*\0\0"; CFileDialog *filedialog; char filename[257]; if (not_applied) { not_applied = 0; m_but_apply.EnableWindow(FALSE); setBandsFromSlpos(); } filedialog = new CFileDialog(FALSE,".eq"); filedialog->m_ofn.lpstrFilter = filter; filedialog->m_ofn.lpstrFile = filename; filename[0] = '\0'; filedialog->m_ofn.nMaxFile = 256; if (filedialog->DoModal() == IDCANCEL) { delete filedialog; return; } delete filedialog; // CFile f; CFileException e; if( !f.Open( filename, CFile::modeCreate | CFile::modeWrite, &e ) ) { ::MessageBox(NULL,"Couldn't open file","Error",MB_OK | MB_ICONEXCLAMATION); // error return; } char buf[1024]; sprintf(buf,"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d " "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n", lslpos[0],lslpos[1],lslpos[2],lslpos[3],lslpos[4],lslpos[5], lslpos[6],lslpos[7],lslpos[8],lslpos[9],lslpos[10],lslpos[11], lslpos[12],lslpos[13],lslpos[14],lslpos[15],lslpos[16],lslpos[17], lslpos[18], rslpos[0],rslpos[1],rslpos[2],rslpos[3],rslpos[4],rslpos[5], rslpos[6],rslpos[7],rslpos[8],rslpos[9],rslpos[10],rslpos[11], rslpos[12],rslpos[13],rslpos[14],rslpos[15],rslpos[16],rslpos[17], rslpos[18]); f.Write(buf,strlen(buf)); for(paramlistelm *p = paramroot.elm;p != NULL;p = p->next) { sprintf(buf,"%.20g %.20g %.20g %d %d\n", (double)p->upper,(double)p->lower,(double)p->gain,(int)p->left,(int)p->right); f.Write(buf,strlen(buf)); } f.Close(); }
void CSubtitleDlDlg::OnOK() { SetStatus(ResStr(IDS_SUBDL_DLG_DOWNLOADING)); for (int i = 0; i < m_list.GetItemCount(); ++i) { if (m_list.GetCheck(i)) { m_selsubs.AddTail(*reinterpret_cast<isdb_subtitle*>(m_list.GetItemData(i))); } } m_fReplaceSubs = IsDlgButtonChecked(IDC_CHECK1) == BST_CHECKED; CMainFrame* pMF = static_cast<CMainFrame*>(GetParentFrame()); if (m_fReplaceSubs) { pMF->m_pSubStreams.RemoveAll(); } CComPtr<ISubStream> pSubStreamToSet; POSITION pos = m_selsubs.GetHeadPosition(); while (pos) { const isdb_subtitle& sub = m_selsubs.GetNext(pos); AppSettings& s = AfxGetAppSettings(); CInternetSession is; CStringA url = "http://" + s.strISDb + "/dl.php?"; CStringA args, ticket, str; args.Format("id=%d&ticket=%s", sub.id, UrlEncode(ticket)); url.Append(args); if (OpenUrl(is, CString(url), str)) { if (pMF->b_UseVSFilter) { if (CComQIPtr<IDirectVobSub> pDVS = pMF->GetVSFilter()) { TCHAR lpszTempPath[_MAX_PATH] = { 0 }; if (::GetTempPath(_MAX_PATH, lpszTempPath)) { CString subFileName(lpszTempPath); subFileName.Append(CString(sub.name)); if (::PathFileExists(subFileName)) { ::DeleteFile(subFileName); } CFile cf; if (cf.Open(subFileName, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyNone)) { cf.Write(str.GetString(), str.GetLength()); cf.Close(); if (SUCCEEDED(pDVS->put_FileName((LPWSTR)(LPCWSTR)subFileName))) { pDVS->put_SelectedLanguage(0); pDVS->put_HideSubtitles(true); pDVS->put_HideSubtitles(false); } ::DeleteFile(subFileName); } } __super::OnOK(); return; } } CAutoPtr<CRenderedTextSubtitle> pRTS(DNew CRenderedTextSubtitle(&pMF->m_csSubLock, &s.subdefstyle, s.fUseDefaultSubtitlesStyle)); if (pRTS && pRTS->Open((BYTE*)(LPCSTR)str, str.GetLength(), DEFAULT_CHARSET, CString(sub.name)) && pRTS->GetStreamCount() > 0) { CComPtr<ISubStream> pSubStream = pRTS.Detach(); pMF->m_pSubStreams.AddTail(pSubStream); if (!pSubStreamToSet) { pSubStreamToSet = pSubStream; } } } } if (pSubStreamToSet) { pMF->SetSubtitle(pSubStreamToSet); AfxGetAppSettings().fEnableSubtitles = true; } __super::OnOK(); }
bool CEvmFile::Load(const char* sFileName) { CFile oFile; if(oFile.Open(sFileName, "r")) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): open file failure", sFileName)); return false; } CEvmFileHead oHead; if(sizeof(oHead) != oFile.Read(&oHead, sizeof(oHead))) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(!CBinary::MemoryCompare(oHead.magic, "CEXE", 4)) m_nFileType = EVM_EXE_FILE; else if(!CBinary::MemoryCompare(oHead.magic, "CDLL", 4)) m_nFileType = EVM_DLL_FILE; else { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } bool bNeedConvert = ((oHead.endian!=0) != IsSmallEndian()); if(bNeedConvert) { oHead.version0 = CBinary::U16Code(oHead.version0); oHead.version1 = CBinary::U16Code(oHead.version1); oHead.version2 = CBinary::U16Code(oHead.version2); } if(oHead.version0 > EVM_FILE_VERSION_0) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): version too new", sFileName)); return false; } else if(oHead.version0 == EVM_FILE_VERSION_0) { if(oHead.version1 > EVM_FILE_VERSION_1) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): version too new", sFileName)); return false; } else if(oHead.version1 == EVM_FILE_VERSION_1) { if(oHead.version2 > EVM_FILE_VERSION_2) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): version too new", sFileName)); return false; } } } ehc_uint pSection[2], nEntry, nTag = 0; bool bReadDone[] = {true,false,false,false,false,false,false,false}; while(true) { if(sizeof(pSection) != oFile.Read(pSection, sizeof(pSection))) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(bNeedConvert) { pSection[0] = CBinary::U32Code(pSection[0]); pSection[1] = (ehc_int)CBinary::U32Code((ehc_uint)pSection[1]); } if((pSection[0] >= EVM_INVALID_SECTION) || bReadDone[pSection[0]] || (pSection[0] <= nTag) || (pSection[1] % sizeof(ehc_uint))) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } nTag = pSection[0]; bReadDone[pSection[0]] = true; switch(nTag) { case EVM_CODESEG_SECTION: m_nCodeSize = pSection[1]; m_pCodeSegment = NULL; if(m_nCodeSize) { m_pCodeSegment = new ehc_char[m_nCodeSize]; if(m_nCodeSize != oFile.Read(m_pCodeSegment, m_nCodeSize)) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } } break; case EVM_DATASEG_SECTION: if(pSection[1] != (ehc_int)sizeof(ehc_uint)) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(sizeof(ehc_int) != oFile.Read(&m_nDataSize, sizeof(ehc_int))) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(bNeedConvert) m_nDataSize = CBinary::U32Code(m_nDataSize); break; case EVM_CONSTSEG_SECTION: m_nConstSize = pSection[1]; m_pConstSegment = NULL; if(m_nConstSize) { m_pConstSegment = new ehc_char[m_nConstSize]; if(m_nConstSize != oFile.Read(m_pConstSegment, m_nConstSize)) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } } break; case EVM_SYMTAB_SECTION: if((pSection[1] % sizeof(CEvmSymbolItem)) || (nFileSize < pSection[1])) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } m_nSymCount = pSection[1] / sizeof(CEvmSymbolItem); if(m_nSymCount) { CEhcSymbolItem* pSymbolTable = new CEhcSymbolItem[m_nSymCount]; if(pSection[1] != oFile.Read(pSymbolTable, pSection[1])) { delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(bNeedConvert) { for(ehc_int i=0; i<m_nSymCount; ++i) { pSymbolTable[i].name = CBinary::U32Code(pSymbolTable[i].name); pSymbolTable[i].type = CBinary::U32Code(pSymbolTable[i].type); pSymbolTable[i].opt = CBinary::U32Code(pSymbolTable[i].opt); pSymbolTable[i].arg = CBinary::U32Code(pSymbolTable[i].arg); } } m_pSymbolTable = new CEvmSymbolItem[m_nSymCount]; for(ehc_int i=0; i<m_nSymCount; ++i) { if(pSymbolTable[i].name >= (ehc_uint)m_nConstSize) { delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } m_pSymbolTable[i].name = m_pConstSegment + pSymbolTable[i].name; m_pSymbolTable[i].type = pSymbolTable[i].type; m_pSymbolTable[i].opt = pSymbolTable[i].opt; m_pSymbolTable[i].addr = NULL; m_pSymbolTable[i].file = NULL; m_pSymbolTable[i].idx = 0xFFFFFFFF; ehc_int nMaxLen = m_nConstSize - pSymbolTable[i].name; ehc_int nNameLen = (ehc_int)CString::StringLength(m_pSymbolTable[i].name, (ehc_uint)nMaxLen); if(nNameLen >= nMaxLen || !nNameLen) {//符号名不合法 delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(!(pSymbolTable[i].type&EVM_SHARE_SYM)) {//可执行文件或动态库符号表中的符号应全是共享符号。 delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } m_pSymbolTable[i].type &= ~EVM_SHARE_SYM; switch(m_pSymbolTable[i].type) { default: delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; case EVM_VARIABLE_SYM: switch(m_pSymbolTable[i].opt) { default: delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; case EHC_UN: //外部变量符号,需要连接 ++m_nExternCount; break; case EHC_DS: //输出变量符号,可被连接 if(pSymbolTable[i].arg >= m_nDataSize) { delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } break; } break; case EVM_FUNCTION_SYM: switch(m_pSymbolTable[i].opt) { default: delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; case EHC_UN: //外部函数符号,需要连接 ++m_nExternCount; break; case EHC_CS: //输出函数符号,可被连接 if(pSymbolTable[i].arg >= m_nCodeSize || (pSymbolTable[i].arg%sizeof(ehc_uint))) {//代码越界或无效指令边界 delete[] pSymbolTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } m_pSymbolTable[i].addr = m_pCodeSegment + pSymbolTable[i].arg; break; case EHC_HS: break; } break; } } delete[] pSymbolTable; } break; case EVM_LIBTAB_SECTION: m_nLibCount = pSection[1] / sizeof(m_nLibCount); m_pLibTable = NULL; if(m_nLibCount) { ehc_uint* pLibTable = new ehc_uint[m_nLibCount]; if(pSection[1] != oFile.Read(pLibTable, pSection[1])) { delete[] pLibTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(bNeedConvert) { for(ehc_int i=0; i<m_nLibCount; ++i) pLibTable[i] = CBinary::U32Code(pLibTable[i]); } m_pLibTable = new ehc_char*[m_nLibCount]; for(ehc_int i=0; i<m_nLibCount; ++i) { if(pLibTable[i] >= (ehc_uint)m_nConstSize) { delete[] pLibTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } m_pLibTable[i] = m_pConstSegment + pLibTable[i]; ehc_int nMaxLen = m_nConstSize - pLibTable[i]; ehc_int nNameLen = (ehc_int)CString::StringLength(m_pLibTable[i], (ehc_uint)nMaxLen); if(nNameLen >= nMaxLen || !nNameLen) {//符号名不合法 delete[] pLibTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } } delete[] pLibTable; } break; case EVM_HOSTTAB_SECTION: m_nHostCount = pSection[1] / sizeof(m_nHostCount); m_pHostTable = NULL; if(m_nHostCount) { ehc_uint* pHostTable = new ehc_uint[m_nHostCount]; if(pSection[1] != oFile.Read(pHostTable, pSection[1])) { delete[] pHostTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(bNeedConvert) { for(ehc_int i=0; i<m_nHostCount; ++i) pHostTable[i] = CBinary::U32Code(pHostTable[i]); } m_pHostTable = new CDynamicLibrary[m_nHostCount]; for(ehc_int i=0; i<m_nHostCount; ++i) { if(pHostTable[i] >= (ehc_uint)m_nConstSize) { delete[] pHostTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } ehc_har* name = m_pConstSegment + pHostTable[i]; ehc_int nMaxLen = m_nConstSize - pHostTable[i]; ehc_int nNameLen = (ehc_int)CString::StringLength(name, (ehc_uint)nMaxLen); if(nNameLen >= nMaxLen || !nNameLen) {//符号名不合法 delete[] pHostTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(!m_pHostTable[i].Load(name)) { delete[] pHostTable; FocpLog(FOCP_LOG_WARNING, ("Load(%s): load host file(%s) failure", sFileName, name)); return false; } } delete[] pHostTable; } break; case EVM_ENTRY_SECTION: if(pSection[1] != (ehc_int)sizeof(ehc_uint)) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(sizeof(ehc_uint) != oFile.Read(&nEntry, sizeof(ehc_uint))) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } if(bNeedConvert) nEntry = CBinary::U32Code(nEntry); if((nEntry >= m_nCodeSize) || (nEntry%sizeof(ehc_uint))) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): invalid file", sFileName)); return false; } m_pEntry = m_pCodeSegment + nEntry; break; } } //扫描符号表,对主机函数进行连接 for(ehc_int i=0; i<m_nSymCount; ++i) { if(m_pSymbolTable[i].opt == EHC_HS) { for(ehc_int j=0; j<m_nHostCount; ++j) { m_pSymbolTable[i].addr = m_pHostTable[i].FindSymbol(m_pSymbolTable[i].name); if(m_pSymbolTable[i].addr) break; } if(m_pSymbolTable[i].addr == NULL) { FocpLog(FOCP_LOG_WARNING, ("Load(%s): host function(%s) link failure", sFileName, m_pSymbolTable[i].name)); return false; } } } m_oFileName = sFileName; return true; }
bool CCDDARipJob::DoWork() { CLog::Log(LOGINFO, "Start ripping track %s to %s", m_input.c_str(), m_output.c_str()); // if we are ripping to a samba share, rip it to hd first and then copy it it the share CFileItem file(m_output, false); if (file.IsRemote()) m_output = SetupTempFile(); if (m_output.empty()) { CLog::Log(LOGERROR, "CCDDARipper: Error opening file"); return false; } // init ripper CFile reader; CEncoder* encoder = nullptr; if (!reader.Open(m_input,READ_CACHED) || !(encoder=SetupEncoder(reader))) { CLog::Log(LOGERROR, "Error: CCDDARipper::Init failed"); return false; } // setup the progress dialog CGUIDialogExtendedProgressBar* pDlgProgress = CServiceBroker::GetGUI()->GetWindowManager().GetWindow<CGUIDialogExtendedProgressBar>(WINDOW_DIALOG_EXT_PROGRESS); CGUIDialogProgressBarHandle* handle = pDlgProgress->GetHandle(g_localizeStrings.Get(605)); int iTrack = atoi(m_input.substr(13, m_input.size() - 13 - 5).c_str()); std::string strLine0 = StringUtils::Format("%02i. %s - %s", iTrack, m_tag.GetArtistString().c_str(), m_tag.GetTitle().c_str()); handle->SetText(strLine0); // start ripping int percent=0; int oldpercent=0; bool cancelled(false); int result; while (!cancelled && (result=RipChunk(reader, encoder, percent)) == 0) { cancelled = ShouldCancel(percent,100); if (percent > oldpercent) { oldpercent = percent; handle->SetPercentage(static_cast<float>(percent)); } } // close encoder ripper encoder->CloseEncode(); delete encoder; reader.Close(); if (file.IsRemote() && !cancelled && result == 2) { // copy the ripped track to the share if (!CFile::Copy(m_output, file.GetPath())) { CLog::Log(LOGERROR, "CDDARipper: Error copying file from %s to %s", m_output.c_str(), file.GetPath().c_str()); CFile::Delete(m_output); return false; } // delete cached file CFile::Delete(m_output); } if (cancelled) { CLog::Log(LOGWARNING, "User Cancelled CDDA Rip"); CFile::Delete(m_output); } else if (result == 1) CLog::Log(LOGERROR, "CDDARipper: Error ripping %s", m_input.c_str()); else if (result < 0) CLog::Log(LOGERROR, "CDDARipper: Error encoding %s", m_input.c_str()); else { CLog::Log(LOGINFO, "Finished ripping %s", m_input.c_str()); if (m_eject) { CLog::Log(LOGINFO, "Ejecting CD"); g_mediaManager.EjectTray(); } } handle->MarkFinished(); return !cancelled && result == 2; }
bool CAPEv2Tag::ReadTag(const char* filename) { if (!filename || !m_dll.Load()) return false; // Read in our tag using our dll apetag *tag = m_dll.apetag_init(); CFile file; if (!file.Open(filename)) { m_dll.apetag_free(tag); return false; } // Create our file reading class ape_file file_api; memset(&file_api, 0, sizeof(ape_file)); file_api.read_func = fread_callback; file_api.seek_func = fseek_callback; file_api.tell_func = ftell_callback; file_api.data = &file; m_dll.apetag_read_fp(tag, &file_api, (char *)filename, 0); if (!tag) return false; if (apefrm_getstr(tag, (char*)"Title")) m_strTitle = apefrm_getstr(tag, (char*)"Title"); if (apefrm_getstr(tag, (char*)"Album")) m_strAlbum = apefrm_getstr(tag, (char*)"Album"); if (apefrm_getstr(tag, (char*)"AlbumArtist")) m_strAlbumArtist = apefrm_getstr(tag, (char*)"AlbumArtist"); if (apefrm_getstr(tag, (char*)"Album Artist")) m_strAlbumArtist = apefrm_getstr(tag, (char*)"Album Artist"); if (apefrm_getstr(tag, (char*)"Artist")) m_strArtist = apefrm_getstr(tag, (char*)"Artist"); if (apefrm_getstr(tag, (char*)"Genre")) m_strGenre = apefrm_getstr(tag, (char*)"Genre"); if (apefrm_getstr(tag, (char*)"Year")) m_strYear = apefrm_getstr(tag, (char*)"Year"); if (apefrm_getstr(tag, (char*)"Track")) m_nTrackNum = atoi(apefrm_getstr(tag, (char*)"Track")); if (apefrm_getstr(tag, (char*)"Media")) { // cd number is usually "CD 1/3" char *num = apefrm_getstr(tag, (char*)"Media"); while (!isdigit(*num) && *num != '\0') num++; if (isdigit(*num)) m_nDiscNum = atoi(num); } if (apefrm_getstr(tag, (char*)"Comment")) m_strComment = apefrm_getstr(tag, (char*)"Comment"); if (apefrm_getstr(tag, (char*)"Lyrics")) m_strLyrics = apefrm_getstr(tag, (char*)"Lyrics"); if (apefrm_getstr(tag, (char*)"Rating")) { // rating number is usually a single digit, 1-5. 0 is unknown. char temp = apefrm_getstr(tag, (char*)"Rating")[0]; if (temp >= '0' && temp < '6') m_rating = temp; } if (apefrm_getstr(tag, (char*)"Compilation")) { char temp = apefrm_getstr(tag, (char*)"Compilation")[0]; if (temp == '1') m_bCompilation = true; } // Replay gain info GetReplayGainFromTag(tag); m_dll.apetag_free(tag); return true; }
int CPartFileConvert::performConvertToeMule(CString folder) { BOOL bWorking; CString filepartindex,newfilename; CString buffer; UINT fileindex; CFileFind finder; CString partfile=folder; folder.Delete(folder.ReverseFind('\\'),folder.GetLength()); partfile=partfile.Mid(partfile.ReverseFind('\\')+1,partfile.GetLength()); UpdateGUI(0,GetResString(IDS_IMP_STEPREADPF),true); filepartindex=partfile.Left(partfile.Find('.')); //int pos=filepartindex.ReverseFind('\\'); //if (pos>-1) filepartindex=filepartindex.Mid(pos+1,filepartindex.GetLength()-pos); UpdateGUI(4,GetResString(IDS_IMP_STEPBASICINF)); CPartFile* file=new CPartFile(); EPartFileFormat eFormat = PMT_UNKNOWN; if (file->LoadPartFile(folder, partfile, &eFormat) == PLR_CHECKSUCCESS) { pfconverting->partmettype = (uint8_t)eFormat; switch (pfconverting->partmettype) { case PMT_UNKNOWN: case PMT_BADFORMAT: delete file; return CONV_BADFORMAT; break; } } else { delete file; return CONV_BADFORMAT; } CString oldfile=folder+_T("\\")+partfile.Left(partfile.GetLength()- ((pfconverting->partmettype==PMT_SHAREAZA)?3:4) ); pfconverting->size=file->GetFileSize(); pfconverting->filename=file->GetFileName(); pfconverting->filehash= EncodeBase16( file->GetFileHash() ,16); UpdateGUI(pfconverting); if (theApp.downloadqueue->GetFileByID(file->GetFileHash())!=0) { delete file; return CONV_ALREADYEXISTS; } if (pfconverting->partmettype==PMT_SPLITTED ) { try { CByteArray ba; ba.SetSize(PARTSIZE); CFile inputfile; int pos1,pos2; CString filename; // just count UINT maxindex=0; UINT partfilecount=0; bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part")); while (bWorking) { bWorking = finder.FindNextFile(); ++partfilecount; buffer=finder.GetFileName(); pos1=buffer.Find('.'); pos2=buffer.Find('.',pos1+1); fileindex=_tstoi(buffer.Mid(pos1+1,pos2-pos1) ); if (fileindex==0) continue; if (fileindex>maxindex) maxindex=fileindex; } float stepperpart; if (partfilecount>0) { stepperpart=(80.0f / partfilecount ); if ((uint64_t)maxindex*PARTSIZE<=pfconverting->size) pfconverting->spaceneeded=(uint64_t)maxindex*PARTSIZE; else pfconverting->spaceneeded=((uint64_t)(pfconverting->size / PARTSIZE) * PARTSIZE)+(pfconverting->size % PARTSIZE); } else { stepperpart=80.0f; pfconverting->spaceneeded=0; } UpdateGUI(pfconverting); if (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < ((uint64_t)maxindex*PARTSIZE) ) { delete file; return CONV_OUTOFDISKSPACE; } // create new partmetfile, and remember the new name file->CreatePartFile(); newfilename=file->GetFullName(); UpdateGUI(8,GetResString(IDS_IMP_STEPCRDESTFILE)); file->m_hpartfile.SetLength( pfconverting->spaceneeded ); uint16_t curindex=0; bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*.part")); while (bWorking) { bWorking = finder.FindNextFile(); //stats ++curindex; buffer.Format(GetResString(IDS_IMP_LOADDATA),curindex,partfilecount); UpdateGUI( 10+(curindex*stepperpart) ,buffer); filename=finder.GetFileName(); pos1=filename.Find('.'); pos2=filename.Find('.',pos1+1); fileindex=_tstoi(filename.Mid(pos1+1,pos2-pos1) ); if (fileindex==0) continue; uint32_t chunkstart=(uint32_t)(fileindex-1) * PARTSIZE ; // open, read data of the part-part-file into buffer, close file inputfile.Open(finder.GetFilePath(),CFile::modeRead|CFile::shareDenyWrite); uint32_t readed=inputfile.Read( ba.GetData() ,PARTSIZE); inputfile.Close(); buffer.Format(GetResString(IDS_IMP_SAVEDATA),curindex,partfilecount); UpdateGUI( 10+(curindex*stepperpart) ,buffer); // write the buffered data file->m_hpartfile.Seek(chunkstart, CFile::begin ); file->m_hpartfile.Write(ba.GetData(),readed); } } catch(CFileException* error) { CString strError(GetResString(IDS_IMP_IOERROR)); TCHAR szError[MAX_CFEXP_ERRORMSG]; if (error->GetErrorMessage(szError, _countof(szError))){ strError += _T(" - "); strError += szError; } LogError(false, _T("%s"), strError); error->Delete(); delete file; return CONV_IOERROR; } file->m_hpartfile.Close(); } // import an external common format partdownload else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza ) { if (!pfconverting->removeSource) pfconverting->spaceneeded = (UINT)GetDiskFileSize(oldfile); UpdateGUI(pfconverting); if (!pfconverting->removeSource && (GetFreeDiskSpaceX(thePrefs.GetTempDir()) < pfconverting->spaceneeded) ) { delete file; return CONV_OUTOFDISKSPACE; } file->CreatePartFile(); newfilename=file->GetFullName(); file->m_hpartfile.Close(); BOOL ret=FALSE; UpdateGUI( 92 ,GetResString(IDS_COPY)); DeleteFile(newfilename.Left(newfilename.GetLength()-4)); if (!PathFileExists(oldfile)) { // data file does not exist. well, then create a 0 byte big one HANDLE hFile = CreateFile( newfilename.Left(newfilename.GetLength()-4) , // file to open GENERIC_WRITE, // open for reading FILE_SHARE_READ, // share for reading NULL, // default security CREATE_NEW, // existing file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attr. template ret= !(hFile == INVALID_HANDLE_VALUE) ; CloseHandle(hFile); } else if (pfconverting->removeSource) ret=MoveFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ); else ret=CopyFile( oldfile, newfilename.Left(newfilename.GetLength()-4) ,false); if (!ret) { file->DeleteFile(); //delete file; return CONV_FAILED; } } UpdateGUI( 94 ,GetResString(IDS_IMP_GETPFINFO)); DeleteFile(newfilename); if (pfconverting->removeSource) MoveFile(folder+_T("\\")+partfile,newfilename); else CopyFile(folder+_T("\\")+partfile,newfilename,false); file->m_hasharray.release(); for ( GapList::iterator it = file->gaplist.begin(); it != file->gaplist.end(); ++it ) { delete *it; } file->gaplist.clear(); if (file->LoadPartFile(thePrefs.GetTempDir(), file->GetPartMetFileName()) != PLR_LOADSUCCESS) { //delete file; file->DeleteFile(); return CONV_BADFORMAT; } if (pfconverting->partmettype==PMT_NEWOLD || pfconverting->partmettype==PMT_SPLITTED ) { file->completedsize = file->m_uTransferred; file->m_uCompressionGain = 0; file->m_uCorruptionLoss = 0; } UpdateGUI( 100 ,GetResString(IDS_IMP_ADDDWL)); theApp.downloadqueue->AddDownload(file,thePrefs.AddNewFilesPaused()); file->SavePartFile(); if (file->GetStatus(true) == PS_READY) theApp.sharedfiles->SafeAddKFile(file); // part files are always shared files if (pfconverting->removeSource) { bWorking = finder.FindFile(folder+_T("\\")+filepartindex+_T(".*")); while (bWorking) { bWorking = finder.FindNextFile(); VERIFY( _tunlink(finder.GetFilePath()) == 0 ); } if (pfconverting->partmettype==PMT_SPLITTED) RemoveDirectory(folder+_T("\\")); } return CONV_OK; }
BOOL CModbusM::SaveToTuFile(CString strFile) { CString strBuf,str; if(m_TuArray.GetSize()<=0) { str.Format("WAIT_RESP_TU=%d\r\n",0); strBuf+=str; str.Format("NUMBER_OF_TU=%d\r\n\r\n",0); strBuf+=str; } else { str.Format("WAIT_RESP_TU=%d\r\n",m_TuArray[0].WAIT_RESP_TU); strBuf+=str; str.Format("NUMBER_OF_TU=%d\r\n\r\n",m_TuArray.GetSize()); strBuf+=str; } for(int i =0; i < m_TuArray.GetSize(); i++) { str.Format("MAKE_TU=%d\r\n",i+1); strBuf+=str; str.Format("TYPE_PRIBOR=%d\r\n",m_TuArray[i].TYPE_PRIBOR); strBuf+=str; str.Format("ADRESS=%d\r\n",m_TuArray[i].ADRESS); strBuf+=str; str.Format("FUNCTION=%d\r\n",m_TuArray[i].FUNCTION); strBuf+=str; str.Format("REGTU_ON=%d\r\n",m_TuArray[i].REGTU_ON); strBuf+=str; str.Format("REGTU_OFF=%d\r\n",m_TuArray[i].REGTU_OFF); strBuf+=str; str.Format("DATATU_ON=%d\r\n",m_TuArray[i].DATATU_ON); strBuf+=str; str.Format("DATATU_OFF=%d\r\n",m_TuArray[i].DATATU_OFF); strBuf+=str; str.Format("TU_CLOSER=%d\r\n",m_TuArray[i].TU_CLOSER); strBuf+=str; str.Format("IEC_ASDU=%d\r\n",m_TuArray[i].IEC_ASDU); strBuf+=str; str.Format("TU_ACT_TRM_ENABLE=%d\r\n",m_TuArray[i].TU_ACT_TRM_ENABLE); strBuf+=str; str.Format("TIMER_SEL_EXEC=%d\r\n",m_TuArray[i].TIMER_SEL_EXEC); strBuf+=str; str.Format("TIMER_ACT_TRM=%d\r\n",m_TuArray[i].TIMER_ACT_TRM); strBuf+=str; str.Format("ADDRESS_TS=%d\r\n",m_TuArray[i].ADDRESS_TS); strBuf+=str; str.Format("TS_ON=%d\r\n",m_TuArray[i].TS_ON); strBuf+=str; str.Format("TS_OFF=%d\r\n",m_TuArray[i].TS_OFF); strBuf+=str; str.Format("ADDRESS_DAMAGE_TU=%d\r\n",m_TuArray[i].ADDRESS_DAMAGE_TU); strBuf+=str; str.Format("MASKA_DAMAGE_TU=%d\r\n",m_TuArray[i].MASKA_DAMAGE_TU); strBuf+=str; str.Format("//%s\r\n\r\n",m_TuArray[i].strCOMMENT); strBuf+=str; } CFile f; try { f.Open(strFile,CFile::modeCreate|CFile::modeWrite); f.Write((void*)strBuf.GetBuffer(),strBuf.GetLength()); f.Close(); } catch(...) { return FALSE; } return TRUE; }
int CDlgBatteryParam::WriteBatteryParam( CString strResourceDtsPath, STRUCT_BATTERY_PARAM* pBatteryParam ) { CString str; POSITION pos,posback; CString str_find,strTemp; int count=0; int mstart=0,mEnd=0; int Num=0,NumMax=0; int i=0; BOOL isExistBat=FALSE; CFile cFile; int nSrcSize; char *pSrcBuf=NULL; //strResourceDtsPath=strResourceDtsPath+_T("xxxx"); if(cFile.Open(strResourceDtsPath, CFile::modeWrite|CFile::modeCreate)){ count=ResourceList.GetCount(); for(pos=ResourceList.GetHeadPosition();pos;) { str_find = ResourceList.GetNext(pos); if(str_find.Find(_T("bat_table"))>=0) { posback=pos; while(Num<20){ //TRACE1("%s\n",str_find); mEnd=str_find.Find(_T(">")); if(mEnd>=0) break; str_find=ResourceList.GetNext(pos); Num++; } NumMax=Num; if(Num>=20){ cFile.Close(); return -2; } str_find.Format(_T("bat_table = <%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d>;"), 0,0,0,pBatteryParam->dwCell,pBatteryParam->dwPullUp,pBatteryParam->dwPullDown, pBatteryParam->dwDischarge[0],pBatteryParam->dwDischarge[1],pBatteryParam->dwDischarge[2],pBatteryParam->dwDischarge[3],pBatteryParam->dwDischarge[4],pBatteryParam->dwDischarge[5], pBatteryParam->dwDischarge[6],pBatteryParam->dwDischarge[7],pBatteryParam->dwDischarge[8],pBatteryParam->dwDischarge[9],pBatteryParam->dwDischarge[10], pBatteryParam->dwCharge[0],pBatteryParam->dwCharge[1],pBatteryParam->dwCharge[2],pBatteryParam->dwCharge[3],pBatteryParam->dwCharge[4],pBatteryParam->dwCharge[5], pBatteryParam->dwCharge[6],pBatteryParam->dwCharge[7],pBatteryParam->dwCharge[8],pBatteryParam->dwCharge[9],pBatteryParam->dwCharge[10]); ResourceList.GetNext(posback); isExistBat=TRUE; } if((Num>0)&&(Num<NumMax)){ str_find.Empty(); Num--; } str_find += _T("\n"); UnicodeToU8(pSrcBuf, nSrcSize, (LPTSTR)(LPCTSTR)str_find); //fputs(pSrcBuf,file); cFile.Write(pSrcBuf, nSrcSize * sizeof(char)); if(pSrcBuf!=NULL) delete[] pSrcBuf; count--; if(count<=1) break; } cFile.Close(); if(!isExistBat) return -1; } else{ return -2; } CString strCmd,strTxt; int iRet=0; int size=0; CString strResult; CString g_strCovert = strRootPath +_T("\\bin\\dtstodtb.bat"); strCmd = CMySpawnConsumer::CovertDtstoDtb(g_strCovert); if (!RunOhterExe(strCmd,&strResult)) { MessageBox(strResult); return -3; } size=GetDtbFileSize(strResourceDtsPath); if(size < 0) g_pPluginLogObject->Record(_T("open %s failed"), strResourceDtbPath); iRet=resource_importDtb(strResourcePath,strResourceDtbPath); if(iRet<0) { g_pPluginLogObject->Record(_T("Import failed :%d"), iRet); return -4; } return 0; }
BOOL CModbusM::LoadFromTuFile(CString strFile) { CFile f; CString strBuf,str; try { if(!f.Open(strFile,CFile::modeRead)) return FALSE; CHAR buffer[4096]; DWORD dwRead=0; // Read in 4096-byte blocks, // remember how many bytes were actually read, // and try to write that many out. This loop ends // when there are no more bytes to read. do { dwRead = f.Read(buffer, 4096); if(dwRead > 0) { int nLen = strBuf.GetLength(); strBuf+=buffer; strBuf.Truncate(nLen+dwRead); } } while (dwRead > 0); f.Close(); //AfxMessageBox(strBuf); strBuf.MakeUpper(); int nIndex = 0; int nProcIndex = -1; strBuf.Remove(';'); int nWaitRespTU = 0; do { nIndex = strBuf.Find("\n"); str = strBuf.Left(nIndex+1); if(str.Find("NUMBER_OF_TU") != -1) { str.TrimLeft("NUMBER_OF_TU"); str.Trim();str.Trim("="); m_TuArray.SetSize(atoi(str)); } if(str.Find("MAKE_TU") != -1) { str.TrimLeft("MAKE_TU"); str.Trim();str.Trim("="); if((atoi(str) > 0)&&(atoi(str) <= m_TuArray.GetSize())) nProcIndex = atoi(str)-1; } if(str.Find("WAIT_RESP_TU") != -1) { str.TrimLeft("WAIT_RESP_TU"); str.Trim();str.Trim("="); //if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) nWaitRespTU = atoi(str); } if(str.Find("TU_CLOSER") != -1) { str.TrimLeft("TU_CLOSER"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TU_CLOSER = atoi(str); } if(str.Find("DATATU_OFF") != -1) { str.TrimLeft("DATATU_OFF"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].DATATU_OFF = atoi(str); } if(str.Find("DATATU_ON") != -1) { str.TrimLeft("DATATU_ON"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].DATATU_ON = atoi(str); } if(str.Find("REGTU_OFF") != -1) { str.TrimLeft("REGTU_OFF"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].REGTU_OFF = atoi(str); } if(str.Find("REGTU_ON") != -1) { str.TrimLeft("REGTU_ON"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].REGTU_ON = atoi(str); } if(str.Find("FUNCTION") != -1) { str.TrimLeft("FUNCTION"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].FUNCTION = atoi(str); } if((str.Find("ADRESS") != -1)&&(str.Find("ADDRESS_TS") == -1)&&(str.Find("ADDRESS_DAMAGE_TU") == -1)) { str.TrimLeft("ADRESS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].ADRESS = atoi(str); } if(str.Find("TYPE_PRIBOR") != -1) { str.TrimLeft("TYPE_PRIBOR"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TYPE_PRIBOR = atoi(str); } if(str.Find("IEC_ASDU") != -1) { str.TrimLeft("IEC_ASDU"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].IEC_ASDU = atoi(str); } if(str.Find("TU_ACT_TRM_ENABLE") != -1) { str.TrimLeft("TU_ACT_TRM_ENABLE"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TU_ACT_TRM_ENABLE = atoi(str); } if(str.Find("TIMER_SEL_EXEC") != -1) { str.TrimLeft("TIMER_SEL_EXEC"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TIMER_SEL_EXEC = atoi(str); } if(str.Find("TIMER_ACT_TRM") != -1) { str.TrimLeft("TIMER_ACT_TRM"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TIMER_ACT_TRM = atoi(str); } if(str.Find("ADDRESS_TS") != -1) { str.TrimLeft("ADDRESS_TS"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].ADDRESS_TS = atoi(str); } if(str.Find("TS_ON") != -1) { str.TrimLeft("TS_ON"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TS_ON = atoi(str); } if(str.Find("TS_OFF") != -1) { str.TrimLeft("TS_OFF"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].TS_OFF = atoi(str); } if(str.Find("ADDRESS_DAMAGE_TU") != -1) { str.TrimLeft("ADDRESS_DAMAGE_TU"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].ADDRESS_DAMAGE_TU = atoi(str); } if(str.Find("MASKA_DAMAGE_TU") != -1) { str.TrimLeft("MASKA_DAMAGE_TU"); str.Trim();str.Trim("="); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].MASKA_DAMAGE_TU = atoi(str); } if((str.Find("//") != -1)&&(str.Find("//_") == -1)) { str.TrimLeft("//"); str.Remove('\n'); str.Remove('\r'); if((nProcIndex >= 0)&&(nProcIndex < m_TuArray.GetSize())) m_TuArray[nProcIndex].strCOMMENT = str; } strBuf.Delete(0,nIndex+1); }while(nIndex != -1); for(int i = 0; i < m_TuArray.GetSize(); i++) m_TuArray[i].WAIT_RESP_TU = nWaitRespTU; } catch(...) { return FALSE; } return TRUE; }
int main3(int argc, char* argv[]) { //( 1 ) (( 3 ) 2 )(( 5 )4)( 6 ) //(\w+)://((\w+\.)*\w+)((/\w*)*)(/\w+\.\w+)? //^协议://网址(x.x...x)/路径(n个\字串)/网页文件(xxx.xxx) //\w 匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。 /W与之相反 匹配任何非单词字符。等价于 '[^A-Za-z0-9_]' //+ 匹配前面的子表达式一次或多次。( ) 标记一个子表达式的开始和结束位置 * 匹配前面的子表达式零次或多次 //? 匹配前面的子表达式零次或一次(等价于 {0,1}),或指明一个非贪婪限定符。 什么是非贪婪限定符 ? 。 // (\w+)://((\w+\.)*\w+)((/\w*)*)(/\w+\.\w+)? //const char *szReg = "(\\w+)://((\\w+\\.)*\\w+)((/\\w*)*)(/\\w+\\.\\w+)?"; //const char *szStr = "http://www.cppprog.com/2009/0112/48.html"; LPSTR pBuffer = NULL; //HTML文件读取 { char szFilename[MAX_PATH] = {"C:\\Lookup\\1.html"}; CFile f; if( f.Open(szFilename)==TRUE ) { FILETIME ftModified; f.GetFileTime(NULL, NULL, &ftModified); DWORD dwSize = f.GetSize(); pBuffer = (LPSTR)new CHAR[dwSize + 1]; f.Read(pBuffer, dwSize); pBuffer[dwSize] = '\0'; f.Close(); } } const char *szReg = "target=\"_blank\"\\>(.+?)\\</a\\>\\</td\\>"; //try { //字符串匹配 boost::regex reg( szReg ); bool r=boost::regex_match( pBuffer , reg); //boost::regex_error err; //cout<< err.what() <<endl; //assert(r); } //catch(boost::regex_error &err) //{ // cout<< err.what() <<endl; // cin.get(); // return 0; //} //catch(...) //{ // cout<<"error"<<endl; // cin.get(); // return 0; //} { //提取子串 boost::cmatch mat; boost::regex reg( szReg ); bool r=boost::regex_match( pBuffer, mat, reg); if(r) //如果匹配成功 { //显示所有子串 for(boost::cmatch::iterator itr=mat.begin(); itr!=mat.end(); ++itr) { // 指向子串对应首位置 指向子串对应尾位置 子串内容 cout << itr->first-pBuffer << ' ' << itr->second-pBuffer << ' ' << *itr << endl; } } //也可直接取指定位置信息 if(mat[4].matched) cout << "Path is" << mat[4] << endl; } delete [] pBuffer; cin.get(); return 0; }