// See ConfigDlg.h for documentation of this method.
BOOL ConfigDlg::ReadBootloaderConfigureArea()
{
    CString filePath;
    m_ctrlImageFile.GetWindowTextW(filePath);
    CFile *cFile = new CFile(filePath.GetBuffer(), CFile::modeReadWrite | CFile::typeBinary);
    filePath.ReleaseBuffer();

    ULONGLONG length = cFile->GetLength();
    if (length < 0x400)
    {
        PrintLog(_T("Warning: File(%s) is smaller than 1K bytes, fill 0xFFs to extend it to 1K bytes."), filePath);
        cFile->SeekToEnd();
        while (length < 0x400)
        {
            cFile->Write("\xFF", 1);
            length++;
        }
        cFile->Flush(); // Flush the 0xFFs to file.
    }

    cFile->Seek(0x3C0, CFile::begin);
    cFile->Read(m_bcaData, 64);

    PrintLog(_T("Read BCA data from image file."));

    delete cFile;

    UpdateDataOfBootloaderConfigureArea(FALSE);

    return TRUE;
}
Example #2
0
//保存关系
bool __cdecl CCompanionManager::SaveCompanion()
{
	//构造关系
	if (m_bNeedUpdate==true)
	{
		//打开文件
		CFile CompanionFile;
		if (CompanionFile.Open(TEXT("Companion.DAT"),CFile::modeCreate|CFile::modeWrite)==FALSE) return false;

		//构造文件头
		tagCompanionFileHead CompanionFileHead;
		CompanionFileHead.wItemSize=sizeof(tagCompanionItem);
		CompanionFileHead.wVersion=MAKEWORD(VER_COMPANION_SUB,VER_COMPANION_MAIN);
		CompanionFileHead.dwFileSize=(DWORD)sizeof(CompanionFileHead)+sizeof(tagCompanionItem)*GetCompanionItemCount();

		//写入文件
		tagCompanionItem * pCompanionItem=NULL;
		CompanionFile.Write(&CompanionFileHead,sizeof(CompanionFileHead));
		for (INT_PTR i=0;i<m_CompanionItemActive.GetCount();i++)
		{
			pCompanionItem=m_CompanionItemActive[i];
			CompanionFile.Write(pCompanionItem,sizeof(tagCompanionItem));
		}

		//关闭文件
		CompanionFile.SetLength(CompanionFileHead.dwFileSize);
		CompanionFile.Flush();
		CompanionFile.Close();

		//设置变量
		m_bNeedUpdate=false;
	}

	return true;
}
Example #3
0
//销毁对话框,将涉密词写入文本文件
BOOL CWordNetDlg::DestroyWindow()
{
	// TODO: 在此添加专用代码和/或调用基类
	//连接数据库
	ADOConn m_AdoConn;
	m_AdoConn.OnInitADOConn();
	CString sql;
	sql.Format(_T("select* from dict"));
	_RecordsetPtr  m_pRecordset;
	m_pRecordset=m_AdoConn.GetRecordSet((_bstr_t)sql);

	//打开词库文件	
	CFile   file;
	file.Open(_T("pattern.txt"),CFile::modeCreate|CFile::modeWrite);
	WORD unicode = 0xFEFF;
	file.Write(&unicode,2);
	
	//更新词库文件
	CString name,weight;
	while(m_AdoConn.m_pRecordset->adoEOF==0)
	{
		name=(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect(_T("name"));
		//AfxMessageBox(name);
		name=name.Trim();
		file.Write(name,wcslen(name)*sizeof(wchar_t));
		file.Write(_T("\r\n"),4);	
		m_pRecordset->MoveNext();
	}
	m_AdoConn.ExitConnect();
	file.Flush();
	file.Close();
	return CDialogEx::DestroyWindow();
}
void CClientCreditsList::SaveList()
{
	if (thePrefs.GetLogFileSaving())
		AddDebugLogLine(false, _T("Saving clients credit list file \"%s\""), CLIENTS_MET_FILENAME);
	m_nLastSaved = ::GetTickCount();

	CString name = thePrefs.GetConfigDir() + CLIENTS_MET_FILENAME;
	CFile file;// no buffering needed here since we swap out the entire array
	CFileException fexp;
	if (!file.Open(name, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){
		CString strError(GetResString(IDS_ERR_FAILED_CREDITSAVE));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		return;
	}

	uint32 count = m_mapClients.GetCount();
	BYTE* pBuffer = new BYTE[count*sizeof(CreditStruct)];
	CClientCredits* cur_credit;
	CCKey tempkey(0);
	POSITION pos = m_mapClients.GetStartPosition();
	count = 0;
	while (pos)
	{
		m_mapClients.GetNextAssoc(pos, tempkey, cur_credit);
		if (cur_credit->GetUploadedTotal() || cur_credit->GetDownloadedTotal())
		{
			MEMCOPY(pBuffer+(count*sizeof(CreditStruct)), cur_credit->GetDataStruct(), sizeof(CreditStruct));
				count++; 
		}
	}

	try{
		uint8 version = CREDITFILE_VERSION;
		file.Write(&version, 1);
		file.Write(&count, 4);
		file.Write(pBuffer, count*sizeof(CreditStruct));
		if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning()))
			file.Flush();
		file.Close();
	}
	catch(CFileException* error){
		CString strError(GetResString(IDS_ERR_FAILED_CREDITSAVE));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (error->GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		error->Delete();
	}

	delete[] pBuffer;
}
Example #5
0
void CDlg3RGSegment::OnBnClickedRgCmdSavevol()
{
	CString strOutputFile;	
	strOutputFile.Format(_T("%s_%dx%dx%d"), SV_EXP_DEFAULTNAME, m_tSubVol.size3D.ndx, m_tSubVol.size3D.ndy, m_tSubVol.size3D.ndz);
	CString strFilters = _T("Raw files (*.raw)|*.raw||");
	CFileDialog dlgSave(FALSE, _T(".raw"), strOutputFile, OFN_OVERWRITEPROMPT, strFilters);

	CFile oFile;
	if (dlgSave.DoModal() == IDOK)
	{
		CFileException ex;
		BOOL bflagOpen = oFile.Open(dlgSave.GetPathName(), CFile::modeWrite | CFile::modeCreate, &ex);
		if(bflagOpen)
		{
			UCHAR* pBuffer1 = NULL;
			UCHAR* pBuffer2 = NULL;
			UCHAR* pCurOrgSlice = NULL;
			UCHAR* pCurSubSlice = NULL;
			UCHAR temp;

			pBuffer1 = new UCHAR[m_tSubVol.size3D.ndx * m_tSubVol.size3D.ndy];
			pBuffer2 = new UCHAR[m_tSubVol.size3D.ndx * m_tSubVol.size3D.ndy];
			INT nOrgFrameSize = m_pDataSet->GetSize().ndx* m_pDataSet->GetSize().ndy;
			INT nSubFrameSize = m_tSubVol.size3D.ndx * m_tSubVol.size3D.ndy;
			
			// for each slice in sub-volume
			for (int i=0; i<m_tSubVol.size3D.ndz; i++)
			{
				// Obtain the corresponding slice of the original volume
				pCurOrgSlice = m_pDataSet->GetDataBuff() + (i + m_tSubVol.pos3D.nZ) * nOrgFrameSize;
				
				// Obtain the original sub-slice
				for (int j=0; j< m_tSubVol.size3D.ndy; j++)
				{
					UINT orgY = j + m_tSubVol.pos3D.nY;
					UINT orgX = m_tSubVol.pos3D.nX;
					CopyMemory(pBuffer1 + j * m_tSubVol.size3D.ndx , pCurOrgSlice + orgY * m_pDataSet->GetSize().ndx + orgX, m_tSubVol.size3D.ndx);
				}

				// Make a mask to the buffer
				Cutout(pBuffer1, pBuffer2, m_tSubVol.size3D.ndx, m_tSubVol.size3D.ndy);


				// Do the masking
				pCurSubSlice = m_tSubVol.pData + i * nSubFrameSize;
				CImgLib::Mask(pCurSubSlice, pBuffer1, pBuffer2, m_tSubVol.size3D.ndx, m_tSubVol.size3D.ndy, 255);

				// Write slice to the file
				oFile.Write(pBuffer1, nSubFrameSize);
			}

			oFile.Flush();
			oFile.Close();
		}	
	}
}
Example #6
0
BOOL RegistryKey::WriteFile()
{
	if (mFileName == "") return FALSE;

    POSITION pos;
    CString key;
    CString val;
	CString data;
	AutoBuf buf(1000);	
	CStringList slist;
    for( pos = mKeyValPairs->GetStartPosition(); pos != NULL; ) {
        mKeyValPairs->GetNextAssoc(pos, key, val);
		String::insertSort(slist, key);
	}

    for (pos = slist.GetHeadPosition(); pos != NULL; ) {
        CString key = slist.GetAt(pos);
		if (mKeyValPairs->Lookup(key, val)) {
			if (key.GetLength() && val.GetLength()) {
				sprintf(buf.p, "%s: %s\r\n", key, val);
				data += buf.p;
			}
		}
		slist.GetNext(pos);
	}


//    for( pos = mKeyValPairs->GetStartPosition(); pos != NULL; ) {
//        mKeyValPairs->GetNextAssoc(pos, key, val);
//        if (key.GetLength() && val.GetLength()) {
//            sprintf(buf.p, "%s: %s\r\n", key, val);
//			data += buf.p;
//        }
//    }
	if (data == "") return FALSE;

	CFile cfile;
	CFileException e;
	if (cfile.Open(mFileName, 
		CFile::modeCreate
		//        |CFile::modeNoTruncate
		|CFile::modeWrite
		//        |CFile::typeText
		|CFile::shareDenyNone,
		&e) == FALSE) {
		return FALSE;
	}

	cfile.Write(data, data.GetLength());
	cfile.Flush();
	cfile.Close();
	return TRUE;


}
Example #7
0
void CAddonCallbacksAddon::FlushFile(const void* addonData, void* file)
{
  CAddonInterfaces* helper = (CAddonInterfaces*) addonData;
  if (!helper)
    return;

  CFile* cfile = (CFile*)file;
  if (!cfile)
    return;

  cfile->Flush();
}
Example #8
0
BOOL CEncryptFile::EncryptFile(CString strKey, CString strSrcFile, CString strDstFile)
{
	if (strSrcFile != strDstFile) {
		if (!CopyFile(strSrcFile, strDstFile, FALSE))
			return  FALSE;
	}
	char *data = NULL;
	CFile *file;
	DWORD dwFileLen = 0;

	file = new CFile;
	if (!file->Open(strDstFile, CFile::shareDenyNone | CFile::modeReadWrite))
	{
		delete file;
		file = NULL;
		return FALSE;
	}

	dwFileLen = file->GetLength();
	data = new char[(int)dwFileLen];
	memset(data, 0, dwFileLen);

	//读取数据
	file->SeekToBegin();
	file->Read(data, dwFileLen);

	//加密
	int iAesLen = m_aes.aes_getsize(dwFileLen);
	char *AesData = new char[iAesLen];
	memset(AesData, 0, iAesLen);

	int iKeyLen = strKey.GetLength();
	char * pkey = new char[iKeyLen];
	memcpy_s(pkey, iKeyLen, strKey, iKeyLen);

	m_aes.aes_encrypt(pkey, data, dwFileLen, AesData, iAesLen);
	delete pkey;

	//写入数据
	file->SeekToBegin();
	file->Write(AesData, iAesLen);
	file->Flush();
	delete[] data;
	delete[] AesData;

	file->Close();
	
	delete file;

	return TRUE;
}
// See ConfigDlg.h for documentation of this method.
void ConfigDlg::WriteBootloaderConfigureArea()
{
    UpdateDataOfBootloaderConfigureArea(TRUE);

    CString filePath;
    m_ctrlImageFile.GetWindowTextW(filePath);
    CFile *cFile = new CFile(filePath.GetBuffer(), CFile::modeWrite | CFile::typeBinary);
    filePath.ReleaseBuffer();

    cFile->Seek(0x3C0, CFile::begin);
    cFile->Write(m_bcaData, 64);
    cFile->Flush();

    PrintLog(_T("Write new BCA data to image file."));
    delete (cFile);
}
Example #10
0
//-----------------------------------------------------------------------------
BOOL CopyFileFromRC(const char* sName, const char* sType, const char* sDest)
{
	HMODULE hMod = AfxGetResourceHandle();

	HRSRC hRes = FindResource(AfxGetResourceHandle(), sName, sType);
	if (!hRes)
	{
		DWORD error = GetLastError();
		return(FALSE);
	}

	HGLOBAL hGlob = LoadResource(hMod, hRes);
	if (!hGlob) return(FALSE);

	DWORD dwSize = SizeofResource(hMod, hRes);
	if (dwSize == 0) return(FALSE);
	if (dwSize > 999999) return(FALSE);

	BYTE* pRes = (BYTE*)LockResource(hGlob);
	if (!pRes) return(FALSE);

	BYTE* pData;
	LT_MEM_TRACK_ALLOC(pData = new BYTE [dwSize + 32],LT_MEM_TYPE_MISC);
	if (!pData) return(FALSE);

	memset(pData, 0, dwSize + 16);
	memcpy(pData, pRes, dwSize);

	CFile file;
	if (!file.Open(sDest, CFile::modeCreate | CFile::modeWrite))
	{
		delete pData;
		return(FALSE);
	}

	file.Write(pData, dwSize);
	file.Flush();
	file.Close();

	delete pData;
	pData = NULL;

	return(TRUE);
}
Example #11
0
//输出信息
void TraceMessage(LPCTSTR pszMessage)
{
	CFile File;
	if ((File.Open(TEXT("TraceData.txt"),CFile::modeWrite)==FALSE)&&
		(File.Open(TEXT("TraceData.txt"),CFile::modeWrite|CFile::modeCreate)==FALSE))
	{
		ASSERT(FALSE);
		return;
	}

	File.SeekToEnd();
	File.Write(pszMessage,lstrlen(pszMessage));
	File.Write(TEXT("\r\n"),lstrlen(TEXT("\r\n")));

	File.Flush();
	File.Close();

	return;
}
Example #12
0
//************************************
// Method:    OnBnClickedCmdSaveslice
// FullName:  CCutoutSegDlg::OnBnClickedCmdSaveslice
// Access:    public 
// Returns:   void
// Qualifier:
//************************************
void CCutoutSegDlg::OnBnClickedCmdSaveslice()
{
	// TODO: Add your control notification handler code here
	BITMAPINFO bm;
	memset(&bm, 0, sizeof(BITMAPINFO));
	bm.bmiHeader = bmInfo;
	Bitmap* bmp = Bitmap::FromBITMAPINFO(&bm,m_pResultImg);
	
	CString strOutputFile;	
	strOutputFile.Format(_T("%s_%dx%d"), SV_EXP_DEFAULTNAME, m_pDataSet->GetSize().ndx, m_pDataSet->GetSize().ndx);
	CString strFilters = _T("Raw files (*.raw)|*.raw|Bitmap file (*.bmp)|*.bmp|JPEG file (*.jpg)|*.jpg||");
	CFileDialog dlgSave(FALSE, _T(".raw"), strOutputFile, OFN_OVERWRITEPROMPT, strFilters);

	CFile oFile;
	if (dlgSave.DoModal() == IDOK)
	{
		CLSID pngClsid;	
		CString ext = dlgSave.GetFileExt();
		if( ext == "raw")
		{			
			CFileException ex;
			BOOL bflagOpen = oFile.Open(dlgSave.GetPathName(), CFile::modeWrite | CFile::modeCreate, &ex);
			if(bflagOpen)
			{
				UINT nLength = m_pDataSet->GetSize().ndx*m_pDataSet->GetSize().ndy;
				oFile.Write(m_pResultByteImg, nLength);	
				oFile.Flush();
				oFile.Close();
			}	
		}
		else if(ext == "bmp")
		{
			CUtility::GetEncoderClsid(L"image/bmp", &pngClsid);
			bmp->Save(dlgSave.GetPathName(), &pngClsid, NULL);
		}
		else if(ext == "jpg")
		{
			CUtility::GetEncoderClsid(L"image/jpeg", &pngClsid);
			bmp->Save(dlgSave.GetPathName(), &pngClsid, NULL);			
		}
	}
}
Example #13
0
void CCommandProcessor::SaveFile(CString strFile, CByteArray &buf)
{
	CFile File;

	if (File.Open(strFile, CFile::modeCreate | CFile::modeWrite))
	{
		File.Write(buf.GetData(), (UINT)buf.GetSize());
		File.Flush();
		File.Close();
		
		if (CIBAConfig::GetInstance()->GetOpenAfterSave())
		{
			ShellExecute(NULL, _T("open"), strFile, NULL, NULL, SW_SHOWNORMAL);
		}
	}
	else
	{
		CIBALog::GetInstance()->Write(_T("SaveFile: Create file failed."));
	}
}
Example #14
0
//************************************
// Method:    OnBnClickedCmdSavevol
// FullName:  CCutoutSegDlg::OnBnClickedCmdSavevol
// Access:    public 
// Returns:   void
// Qualifier:
//************************************
void CCutoutSegDlg::OnBnClickedCmdSavevol()
{
	CString strOutputFile;	
	strOutputFile.Format(_T("%s_%dx%dx%d"), SV_EXP_DEFAULTNAME, m_pDataSet->GetSize().ndx, m_pDataSet->GetSize().ndx,m_pDataSet->GetSize().ndz);
	CString strFilters = _T("Raw files (*.raw)| *.raw||");
	CFileDialog dlgSave(FALSE, _T(".raw"), strOutputFile, OFN_OVERWRITEPROMPT, strFilters);
	UCHAR* pByteBuffer = new UCHAR[m_pDataSet->GetSize().ndx * m_pDataSet->GetSize().ndy];
	CFile oFile;	
	CFileException ex;

	if (dlgSave.DoModal() == IDOK)
	{
		UINT nLength = m_pDataSet->GetSize().ndx*m_pDataSet->GetSize().ndy;
		CString path = dlgSave.GetPathName();
		BOOL bflagOpen = oFile.Open(dlgSave.GetPathName(), CFile::modeWrite | CFile::modeCreate, &ex);
		if(bflagOpen)
		{
			//for (int iSlice=m_pDataSet->GetSize().ndz-1 ; iSlice >=0 ; iSlice--)
			for (int iSlice=0; iSlice < m_pDataSet->GetSize().ndz; iSlice++)
			{
				//Get Raw Slice
				GetRawSliceFromDataSet(iSlice);

				//Cut it out
				CSize sliceSize(m_pDataSet->GetSize().ndx,m_pDataSet->GetSize().ndy);
				CutOut(m_pSourceByteImg, pByteBuffer, sliceSize.cx, sliceSize.cy);

				//Write to file
				oFile.Write(pByteBuffer, nLength);
			}
			oFile.Flush();			
		}		
		oFile.Close();
	}
	delete[] pByteBuffer;
	//Re update m_pSourceByteImg slice back to current slice
	UpdateSourceSlice();
}
Example #15
0
void Filter::OnBnClickedSave()
{
	transmitting = 0;
	buttonFiltering.SetWindowTextA("Start Filtering");
	stopFiltering();


	 TCHAR szFilters[]= _T("Filter Files (*.flt)\0*.flt\0");
	 CFileDialog fileDlg(FALSE, _T("flt"), _T("*.flt"), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilters);
	 if(fileDlg.DoModal() == IDOK){
		CString pathName = fileDlg.GetPathName();
		CFile cfile;
		cfile.Open((pathName), CFile::modeCreate | CFile::modeReadWrite);
		CString strtowrite;
		CString buffer;


		for(int i = 0; i < listControl.GetItemCount(); i++){
			if(listControl.GetItemText(i,2).Compare("Exclude") == 0){
				strtowrite += "Exclude,";
			}else{
				strtowrite += "Include,";
			}
			strtowrite += listControl.GetItemText(i,1) + ",";
			if(listControl.GetItemText(i,0).Compare("Enabled") == 0){
				strtowrite += "True";
			}else{
				strtowrite += "False";
			}
			strtowrite +="," + listControl.GetItemText(i,3);
			strtowrite += "\n";
		}
		cfile.Write(strtowrite, strtowrite.GetLength());         
		cfile.Flush();
	}
}
Example #16
0
//************************************
// Method:    OnBnClickedCmdSaveallslices
// FullName:  CCutoutSegDlg::OnBnClickedCmdSaveallslices
// Access:    public 
// Returns:   void
// Qualifier:
//************************************
void CCutoutSegDlg::OnBnClickedCmdSaveallslices()
{
	// User prompt to get the information: directory, file extension
	CSegmentExportDlg dlgSave;
	CString sDirPath = _T(".");
	CString sFileExt;
	CString strOutputFile;	
	strOutputFile.Format(_T("%s_%dx%d"),SV_EXP_DEFAULTNAME, m_pDataSet->GetSize().ndx, m_pDataSet->GetSize().ndx);

	CSize sliceSize(m_pDataSet->GetSize().ndx,m_pDataSet->GetSize().ndy);
	UCHAR* pBuffer = new UCHAR[sliceSize.cx * sliceSize.cy * 3];
	UCHAR* pByteBuffer = new UCHAR[sliceSize.cx * sliceSize.cy];
	if (dlgSave.DoModal() == IDOK)
	{
		sDirPath = dlgSave.m_sDirPath;
		sFileExt = dlgSave.m_sExt;
		// TODO: Add your control notification handler code here
		for (int iSlice=0; iSlice < m_pDataSet->GetSize().ndz; iSlice++)
		{
			//Get Raw Slice
			GetRawSliceFromDataSet(iSlice);

			//Cut it out
			CutOut(m_pSourceByteImg, pByteBuffer, sliceSize.cx, sliceSize.cy);
	

			//Save it
			CString numbers;
			numbers.Format(_T("_%.3d"), iSlice);
			CString FullPath = sDirPath + strOutputFile + numbers + _T(".")+ sFileExt;

			for (int i=0; i<sliceSize.cx * sliceSize.cy; i++)
			{			
				memset(pBuffer + i*3, pByteBuffer[i], 3);
			}

			BITMAPINFO bm;
			memset(&bm, 0, sizeof(BITMAPINFO));
			bm.bmiHeader = bmInfo;
			Bitmap* bmp = Bitmap::FromBITMAPINFO(&bm,pBuffer);

			CLSID pngClsid;	
			if( sFileExt == "raw")
			{			
				CFile oFile;
				CFileException ex;
				BOOL bflagOpen = oFile.Open(FullPath, CFile::modeWrite | CFile::modeCreate, &ex);
				if(bflagOpen)
				{
					UINT nLength = m_pDataSet->GetSize().ndx*m_pDataSet->GetSize().ndy;
					oFile.Write(pByteBuffer, nLength);		
					oFile.Flush();
					oFile.Close();
				}	
			}
			else if(sFileExt == "bmp")
			{
				CUtility::GetEncoderClsid(L"image/bmp", &pngClsid);
				bmp->Save(FullPath, &pngClsid, NULL);
			}
			else if(sFileExt == "jpg")
			{
				CUtility::GetEncoderClsid(L"image/jpeg", &pngClsid);
				bmp->Save(FullPath, &pngClsid, NULL);			
			}
		}
	}

	delete[] pBuffer;
	delete[] pByteBuffer;

	//Re update m_pSourceByteImg slice back to current slice
	UpdateSourceSlice();
	
}
Example #17
0
//将字节流转换为文件
BOOL CXmlBase::ConvertBSTR2File(const CString& sPathfilename, const BSTR& pSrc)
{
	char* pTemp;
	if (NULL == pSrc) return FALSE;
	pTemp = _com_util::ConvertBSTRToString(pSrc);
	if (NULL == pTemp) return FALSE;

	int nCodedLen = SysStringByteLen(pSrc); //编码的buffer长度
	if (nCodedLen <= 0) return FALSE;

	nCodedLen = Base64DecodeGetRequiredLength(nCodedLen);
	CString strSrc = pTemp;
	//if (!ConvertBSTR2CString(strSrc, pSrc)) return FALSE;

	int nDecodeLen = nCodedLen; //保存解码后的buffer
	char * pDecode = new char[nDecodeLen];
	memset(pDecode, NULL, nDecodeLen);
	
	BOOL bDecode = ATL::Base64Decode(strSrc, strSrc.GetLength(), (BYTE*)pDecode, &nDecodeLen);
	//WRITELOG("解码%s,解码后的数据长度为[%d]个字节", (bDecode ? _T("成功") : _T("失败")), nDecodeLen);

	delete[] pTemp;
	pTemp = NULL;

	DWORD nTotalWritten = 0;
//	DWORD nWriteSize = nDecodeLen;
	if (bDecode)
	{
		//写文件
		CFile file;
		if (file.Open((LPCTSTR)sPathfilename, CFile::modeCreate | CFile::modeWrite))
		{
			if (file.m_hFile == CFile::hFileNull) return FALSE;

//			DWORD nNumberOfBytesWritten = 0;
			//char *p = pDecode;
			file.SeekToBegin();
			file.Write(pDecode, nDecodeLen);
			file.Flush();
			nTotalWritten = nDecodeLen;

			//nWriteSize = 4096;
			//if (0 == nDecodeLen / 4096)
			//{
			//	nWriteSize = nDecodeLen % 4096;
			//}

			//while (nWriteSize > 0 
			//	&& WriteFile(file.m_hFile, p, nWriteSize, &nNumberOfBytesWritten, NULL) && nNumberOfBytesWritten > 0)
			//{
			//	p += nNumberOfBytesWritten;
			//	nTotalWritten += nNumberOfBytesWritten;
			//	if (0 == (nDecodeLen - nTotalWritten) / 4096)
			//	{
			//		nWriteSize = (nDecodeLen - nTotalWritten) % 4096;
			//	}
			//}
			file.Close();
		}
	}

	delete[] pDecode;
	pDecode = NULL;

	if (nTotalWritten != (DWORD)nDecodeLen || (!bDecode))
	{
		return FALSE;
	}
	return TRUE;
}
Example #18
0
FileState ReceiveFile(SOCKET socket, HWND hWrapperWnd, LPCTSTR strFilePathName, ULONGLONG llStartAt)
{

	PostMessage(hWrapperWnd, WM_FILE_OPERATE_BEGIN, 0, 0);

	FileState MyFileState = S_FileOK, YouFileState = S_FileOK;

	//open file
	CString strFileName = strFilePathName;
	CFile LocalFile;
	UINT uOpMode = llStartAt > 0 ? (CFile::modeReadWrite | CFile::typeBinary) : (CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary);

	if (IsFileExist(strFileName))
	{
		if (!DropReadOnly(strFileName))
			MyFileState = S_CreateFileFailed;
	}

	if(!LocalFile.Open(strFileName, uOpMode))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_CreateFileFailed;
	}

	if (MyFileState != S_CreateFileFailed)
	{
		ULONGLONG uSeeked = LocalFile.Seek(llStartAt, CFile::begin);
		if (uSeeked != llStartAt)
		{
			MyFileState = S_CreateFileFailed;
		}
	}

	//receive you file operate state
	if(!ReceiveData(socket, (char*)&YouFileState, sizeof(FileState)))
	{
		LocalFile.Close();
		return S_SocketError;
	}

	//send my file operate state
	if(!SendData(socket, (char*)&MyFileState, sizeof(FileState)))
	{
		if(MyFileState != S_CreateFileFailed)
			LocalFile.Close();
		return S_SocketError;
	}

	if(MyFileState != S_FileOK) return MyFileState;
	if(YouFileState != S_FileOK) return YouFileState;

	BasicFileInfo basicFileInfo;
	if(!ReceiveData(socket, (char*)(&basicFileInfo), sizeof(basicFileInfo)))
	{
		LocalFile.Close();
		//DeleteFile(strFilePathName);
		return S_SocketError;
	}
	
	ULONGLONG nTotalRead = llStartAt;
	ULONGLONG nDes = basicFileInfo.Size > 1024 * 1024 * 1024 ? 1024 * 1024 : 1024;
	PostMessage(hWrapperWnd, WM_FILE_SETRANGE_MESSAGE, (WPARAM)( basicFileInfo.Size / nDes), (LPARAM)0);

	PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nTotalRead / nDes), 0);
	ULONGLONG nRead = llStartAt;
	ULONGLONG nResCount = 0;
	ULONGLONG nRealRead = 0;

	FileDataEx fileData;

	if (gl_pLogger) gl_pLogger->log_info("ReceiveFile Begin to send: %s", strFilePathName);
	
	bool *pbstatus = NULL;
	SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&pbstatus);
	//receive loop
	while(1)
	{		
		if (!ReceiveData(socket, (char*)(&fileData), sizeof(fileData)))
			return S_SocketError;

		if (fileData.data.nLength == 0)
			break;

		if (fileData.state == S_IStop)
		{
			LocalFile.Close();
			//DeleteFile(strFilePathName);
			return S_OtherSideStop;
		}

		FileState MyState = S_FileOK;
		try{
			if (fileData.data.nLength > 0)
				LocalFile.Write(fileData.data.Buf, fileData.data.nLength);
		}
		catch(...){
			MyState = S_WriteFileFailed;
		}
		nRealRead = nRealRead + fileData.data.nLength;

		nTotalRead = nTotalRead + fileData.data.nLength;
		PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nTotalRead / nDes), 0);

		if(fileData.state == S_Finished)
		{
			if (nRealRead > 0)
				LocalFile.Flush();
			LocalFile.Close();
			return fileData.state;
		}
		
		if(fileData.state == S_ReadFileFailed)
		{
			LocalFile.Close();
			//DeleteFile(strFilePathName);
			return fileData.state;
		}


		nResCount++;
		if(nResCount % READWRITESTATUS == 0)
		{
			nResCount = 0;
			
			FileState MyState,YouState;

			MyState = (*pbstatus) ? S_FileContinue : S_IStop;
			//SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&MyState);
			
			if(!ReceiveData(socket, (char*)&YouState, sizeof(FileState)))
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_SocketError;
			}

			if(!SendData(socket, (char*)&MyState, sizeof(FileState)))
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_SocketError;
			}
			
			if(MyState == S_IStop)
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_IStop;
			}

			if(YouState == S_WriteFileFailed || YouState == S_IStop)
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				if(YouState == S_IStop) 
					YouState = S_OtherSideStop;
				return YouState;
			}
		}
	}

	return S_Finished;
}