예제 #1
1
/**
 * \brief Start parsing.
 * \param LogProc A Pointer to the logging procedure.
 */
void CAuxParser::Parse(PFNLOGPROC LogProc)
{
	m_LogProc = LogProc;
	m_Errors = 0;
	m_BibData.Empty();
	m_BibStyle.Empty();
	CString str;
	if (!m_AuxFile.IsEmpty()) {
		CFile f;
		CFileException ex;
		if (f.Open(m_AuxFile, CFile::modeRead | CFile::shareDenyWrite, &ex)) {
			str.Format(AfxLoadString(IDS_STRING_PARSING), m_AuxFile);
			AddLog(str);
			CBibReader reader(&f);
			ParseFile(&reader);
			f.Close();
		} else {
			m_Errors++;
			TCHAR msg[MAX_PATH];
			ex.GetErrorMessage(msg, MAX_PATH);
			str.Format(AfxLoadString(IDS_STRING_ERROR), msg);
			AddLog(str);
		}
	}
}
예제 #2
1
//-----------------------------------------------------------------------------
// Does:   Open a File And Load It Into IPicture (Interface)
// ~~~~    (.BMP .DIB .EMF .GIF .ICO .JPG .WMF)
//
// InPut:  sFilePathName - Path And FileName Target To Save
// ~~~~~   
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicViewer::Load(CString sFilePathName)
//=============================================================================
{
    BOOL bResult = FALSE;
    CFile PictureFile;
    CFileException e;
    int	nSize = 0;
    
    if(m_IPicture != NULL) FreePictureData(); // Important - Avoid Leaks...
    
    if(PictureFile.Open(sFilePathName, CFile::modeRead | CFile::typeBinary, &e))
    {
        nSize = PictureFile.GetLength();
        BYTE* pBuffer = new BYTE[nSize];
        
        if(PictureFile.Read(pBuffer, nSize) > 0)
        {
			// 防止图像文件数据有错(目前的问题是无结束符),导致OleLoadPicture无响应 [6/22/2009 guowenpeng]
			if ((pBuffer[nSize - 2] != 0xff)
				|| (pBuffer[nSize - 1] != 0xd9))	// 0xffd9: jpeg文件结束标志
			{
				pBuffer[nSize - 2] = 0xff;
				pBuffer[nSize - 1] = 0xd9;
			}

            if(LoadPictureData(pBuffer, nSize))	bResult = TRUE;
        }
        
        PictureFile.Close();
        delete [] pBuffer;
    }
    else // Open Failed...
    {
        TCHAR szCause[255];
        e.GetErrorMessage(szCause, 255, NULL);
        TRACE( "%s\n", szCause );
        // 		HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
        // 		MessageBoxEx(hWnd, szCause, ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
        bResult = FALSE;
    }
    
    m_Weight = nSize; // Update Picture Size Info...
    
    if(m_IPicture != NULL) // Do Not Try To Read From Memory That Is Not Exist...
    { 
        m_IPicture->get_Height(&m_Height);
        m_IPicture->get_Width(&m_Width);
        // Calculate Its Size On a "Standard" (96 DPI) Device Context
        m_Height = MulDiv(m_Height, 96, HIMETRIC_INCH);
        m_Width  = MulDiv(m_Width,  96, HIMETRIC_INCH);
    }
    else // Picture Data Is Not a Known Picture Type
    {
        m_Height = 0;
        m_Width = 0;
        bResult = FALSE;
    }
    
    return(bResult);
}
예제 #3
0
void CTextPadDlg::OnBnClickedLoadbtn()
{
	// TODO: Add your control notification handler code here
	char szFilter[] = "(*.txt) | All Files(*.*)|*.*||";
	CFileDialog dlg(TRUE, "txt", "*.txt", OFN_HIDEREADONLY, szFilter);
	if(IDOK == dlg.DoModal()){
		CString strPathName = dlg.GetPathName();
		
		CStdioFile fp;
		CFileException e;
		
		if(!fp.Open(strPathName, CFile::modeRead, &e)) {
			e.ReportError();
			return;
		}

		CString str = "";
		CString tmp = "";
		
		while(fp.ReadString(tmp)){
			str += tmp;
			str += "\r\n";
		}
		UpdateData(FALSE);
		textpad.SetWindowText(str);
		fp.Close();
	}
}
예제 #4
0
void CKmlDlg::convert_all_file()
{
	int i;
	CString temp;
	for(i=0;i<NumOfFile;i++)
	{
		CFileException ef;
		try
		{		        
			if(!Fsource.Open(FilePath[i],CFile::modeRead,&ef))
			{
				ef.ReportError();
				continue;
			}
			IsFSourceOpen = true;

			kml_filename = FileName[i];
			int find = kml_filename.Find(".");
			kml_filename = kml_filename.Mid(0,find);   

			Convert();
			
			temp.Format("%s OK",FileName[i]);
			m_check[i].SetWindowText(temp);
			m_check[i].SetCheck(BST_CHECKED);	
		}
		catch(CFileException *fe)
		{
			fe->ReportError();
			fe->Delete();
		}	
	}
}
예제 #5
0
void CTextPadDlg::OnBnClickedSavebtn()
{
	// TODO: Add your control notification handler code here
	//CFileDialog를 숨긴파일 읽지않고, 
	//같은 이름의 파일이 있을시 물어보는 옵션으로 열기
	char szFilter[] = "(*.txt) | All Files(*.*)|*.*||";
	CFileDialog dlg(FALSE, "txt", "*.txt",
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT  , szFilter);
	
	if(IDOK == dlg.DoModal()){
		CString strPathName = dlg.GetPathName();

		CStdioFile fp;
		CFileException e;
		
		if(!fp.Open(strPathName,CFile::modeWrite|CFile::modeCreate, &e)) {
			e.ReportError();
			return;
		}

		UpdateData(TRUE);
		CString str;
		textpad.GetWindowText(str);
		str.Replace("\r\n", "\n");

		fp.WriteString(str);
		fp.Close();
	}
}
예제 #6
0
파일: CrossDlg.cpp 프로젝트: fdiskcn/Whorld
bool CCrossDlg::Save(int Sel)
{
	ASSERT(Sel >= 0 && Sel < SELS);
	CPathStr	FileName;
	GetName(Sel, FileName);
	CFileDialog	fd(FALSE, EXT_PATCH, FileName, OFN_OVERWRITEPROMPT, LDS(IDS_FILTER_PATCH));
	if (fd.DoModal() != IDOK)
		return(FALSE);
	CStdioFile	fp;
	CFileException	e;
	if (!fp.Open(fd.GetPathName(), CFile::modeCreate | CFile::modeWrite, &e)) {
		e.ReportError();
		return(FALSE);
	}
	CPatch	Patch;
	Patch = m_Info[Sel];	// assign parm info
	m_Frm->GetPatch(Patch);	// get master and main info
	if (!Patch.Write(fp))
		return(FALSE);
	m_Modified[Sel] = FALSE;
	FileName = fd.GetFileName();
	FileName.RemoveExtension();
	SetName(Sel, FileName);
	return(TRUE);
}
예제 #7
0
파일: RenJS.cpp 프로젝트: gomoku/RenLib
RenJS::Result
RenJS::addGame(const CString& strFile)
{
	CFileException e;

	if (!mGameFile.Open(strFile, CFile::modeRead, &e))
	{
		mResult = OPEN_FILE_ERROR;
	}
	else
	{
		try
		{
			parseGame();

			if (mMoves.size() == 0)
			{
				mResult = EMPTY_ERROR;
			}
		}
		catch (Exception e)
		{
			mResult = e.getErrorCause();
		}

		mGameFile.Close();
	}

	if (mResult == VALID)
	{
		mResult = CheckMoves();
	}

	return mResult;
}
예제 #8
0
bool CKnownFileList::LoadKnownFiles()
{
	CString fullpath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR);
	fullpath.Append(KNOWN_MET_FILENAME);
	CSafeBufferedFile file;
	CFileException fexp;
	if (!file.Open(fullpath,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){
		if (fexp.m_cause != CFileException::fileNotFound){
			CString strError(_T("Failed to load ") KNOWN_MET_FILENAME _T(" file"));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(LOG_STATUSBAR, _T("%s"), strError);
		}
		return false;
	}
	setvbuf(file.m_pStream, NULL, _IOFBF, 16384);

	CKnownFile* pRecord = NULL;
	try {
		uint8 header = file.ReadUInt8();
		if (header != MET_HEADER && header != MET_HEADER_I64TAGS){
			file.Close();
			LogError(LOG_STATUSBAR, GetResString(IDS_ERR_SERVERMET_BAD));
			return false;
		}
		AddDebugLogLine(false, _T("Known.met file version is %u (%s support 64bit tags)"), header, (header == MET_HEADER) ? _T("doesn't") : _T("does")); 

		UINT RecordsNumber = file.ReadUInt32();
		for (UINT i = 0; i < RecordsNumber; i++) {
			pRecord = new CKnownFile();
			if (!pRecord->LoadFromFile(&file)){
				TRACE(_T("*** Failed to load entry %u (name=%s  hash=%s  size=%I64u  parthashs=%u expected parthashs=%u) from known.met\n"), i, 
					pRecord->GetFileName(), md4str(pRecord->GetFileHash()), pRecord->GetFileSize(), pRecord->GetHashCount(), pRecord->GetED2KPartHashCount());
				delete pRecord;
				pRecord = NULL;
				continue;
			}
			SafeAddKFile(pRecord);
			pRecord = NULL;
		}
		file.Close();
	}
	catch(CFileException* error){
		if (error->m_cause == CFileException::endOfFile)
			LogError(LOG_STATUSBAR, GetResString(IDS_ERR_SERVERMET_BAD));
		else{
			TCHAR buffer[MAX_CFEXP_ERRORMSG];
			error->GetErrorMessage(buffer, ARRSIZE(buffer));
			LogError(LOG_STATUSBAR, GetResString(IDS_ERR_SERVERMET_UNKNOWN),buffer);
		}
		error->Delete();
		delete pRecord;
		return false;
	}

	return true;
}
예제 #9
0
CString CGravador::GetTempFile(CString strSql)
{
	// cria o arquivo .SQL no diretório temp
	CString strFile;
	CStdioFile cFile;
	BOOL bResFile;
	CFileException ex;

	CString strPath;

	// obtém o diretório temp do computador local.
	// Get the executable file path
	CString szFilePath;
	szFilePath = CUtil::GetFilePath();

	strFile = szFilePath + _T("\\temp.cfg");
	bResFile = cFile.Open(strFile, CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::shareExclusive, &ex);
	if (!bResFile)
	{
		TCHAR szError[1024];
		ex.GetErrorMessage(szError, 1024);
		m_debugLog.Log(LOG_ERROR, _T("Não foi possível abrir o arquivo %s, erro = %s") , strFile, szError);
	}

	// escreve a string de script no arquivo.
	if (cFile.m_hFile != CFile::hFileNull)
	{
		cFile.WriteString(strSql);
		cFile.Close();
	}

	// devolve o nome do arquivo para ser deletado e também para usar o diretório temp na linha de comando.
	m_debugLog.Log(LOG_INFO, strFile);
	return strFile;
}
예제 #10
0
BOOL CTextFile::ReadTextFile( CString& filename, CStringArray& contents )
/* ============================================================
	Function :		CTextFile::ReadTextFile
	Description :	Will read the contents of the file filename 
					into the CStringArray contents, one line 
					from the file at a time.
					If filename is empty, the standard file 
					dialog will be displayed, and - if OK is 
					selected - filename will contain the 
					selected filename on return.

	Return :		BOOL					-	TRUE if OK. 
												GetErrorMessage 
												will contain errors.
	Parameters :	CString& filename		-	file to read from
					CStringArray& contents	-	will be filled 
												with the contents 
												of the file

   ============================================================*/
{

	ClearError();
	BOOL result = TRUE;

	if( filename.IsEmpty() )
		result = GetFilename( FALSE, filename );

	if( result )
	{
		CStdioFile file;
		CFileException feError;

		if( file.Open( filename, CFile::modeRead, &feError ) )
		{

			contents.RemoveAll();

			CString line;
			while( file.ReadString( line ) )
				contents.Add( line );

			file.Close();

		}
		else
		{

			TCHAR	errBuff[256];
			feError.GetErrorMessage( errBuff, 256 );
			m_error = errBuff;
			result = FALSE;

		}
	}

	return result;

}
예제 #11
0
void CClientCreditsList::SaveList()
{
	if (thePrefs.GetLogFileSaving())
		AddDebugLogLine(false, _T("Saving clients credit list file \"%s\""), CLIENTS_MET_FILENAME);
	m_nLastSaved = ::GetTickCount();

	CString name = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + 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())
		{
			memcpy(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));
		//  Comment UI
		//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;
}
예제 #12
0
파일: ZipStorage.cpp 프로젝트: F5000/spree
bool CZipStorage::OpenFile(LPCTSTR lpszName, UINT uFlags, bool bThrow)
{
	CFileException* e = new CFileException;
	BOOL bRet = m_file.Open(lpszName, uFlags | CFile::shareDenyWrite, e);
	if (!bRet && bThrow)
		throw e;
	e->Delete();
	return bRet != 0;
}
예제 #13
0
BOOL CTextFile::AppendFile( CString& filename, const CStringArray& contents )
/* ============================================================
	Function :		CTextFile::AppendFile
	Description :	Appends contents to filename. Will create 
					the file if it doesn't already exist.
					If filename is empty, the standard file 
					dialog will be displayed, and - if OK is 
					selected - filename will contain the 
					selected filename on return.
					
	Return :		BOOL					-	TRUE if OK. 
												GetErrorMessage 
												will return 
												errors
	Parameters :	CString& filename		-	file to write to
					CStringArray contents	-	contents to write

   ============================================================*/
{

	CStdioFile file;
	CFileException feError;
	BOOL result = TRUE;

	if( filename.IsEmpty() )
		result = GetFilename( TRUE, filename );

	if( result )
	{
		// Write the file
		if( file.Open( filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate, &feError ) )
		{

			file.SeekToEnd();

			int max = contents.GetSize();
			for( int t = 0 ; t < max ; t++ )
				file.WriteString( contents[ t ] + m_eol );

			file.Close();

		}
		else
		{

			// Set error message
			TCHAR	errBuff[256];
			feError.GetErrorMessage( errBuff, 256 );
			m_error = errBuff;
			result = FALSE;

		}
	}

	return result;

}
예제 #14
0
BOOL CTextFile::WriteTextFile( CString& filename, const CString& contents )
/* ============================================================
	Function :		CTextFile::WriteTextFile
	Description :	Writes contents to filename. Will create 
					the file if it doesn't already exist, 
					overwrite it otherwise.
					If filename is empty, the standard file 
					dialog will be displayed, and - if OK is 
					selected - filename will contain the 
					selected filename on return.
					
	Return :		BOOL					-	TRUE if OK. 
												GetErrorMessage 
												will return 
												errors
	Parameters :	CString& filename		-	file to write to
					const CString& contents	-	contents to write

   ============================================================*/
{

	// Error checking
	ClearError();

	CFile file;
	CFileException feError;
	BOOL result = TRUE;

	if( filename.IsEmpty() )
		result = GetFilename( TRUE, filename );

	if( result )
	{
		// Write the file
		if( file.Open( filename, CFile::modeWrite | CFile::modeCreate, &feError ) )
		{

			file.Write( contents, contents.GetLength() );
			file.Close();

		}
		else
		{

			// Set error message
			TCHAR	errBuff[256];
			feError.GetErrorMessage( errBuff, 256 );
			m_error = errBuff;
			result = FALSE;

		}
	}

	return result;

}
예제 #15
0
bool CFriendList::AddEmfriendsMetToList(const CString& strFile)
{
	CSafeBufferedFile file;
	CFileException fexp;
	if ( !file.Open(strFile, CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary, &fexp) )
	{
		if ( fexp.m_cause != CFileException::fileNotFound )
		{
			CString strError(GetResString(IDS_ERR_READEMFRIENDS));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if ( fexp.GetErrorMessage(szError,MAX_CFEXP_ERRORMSG) )
			{
				strError += _T(" - ");
				strError += szError;
			}
			AddLogLine(true, _T("%s"), strError);
		}
		return false;
}
	try
	{
		uint8 header = file.ReadUInt8();
		if ( header != MET_HEADER )
		{
			file.Close();
			return false;
		}
		UINT nRecordsNumber = file.ReadUInt32();
		for (UINT i = 0; i < nRecordsNumber; i++)
		{
			CFriend* Record =  new CFriend();
			Record->LoadFromFile(&file);
			if ( !IsAlreadyFriend(Record->m_abyUserhash) )
				m_listFriends.AddTail(Record);
		}
		file.Close();
	}
	catch ( CFileException* error )
	{
		if ( error->m_cause == CFileException::endOfFile )
			AddLogLine(true,GetResString(IDS_ERR_EMFRIENDSINVALID));
		else
		{
			TCHAR buffer[MAX_CFEXP_ERRORMSG];
			error->GetErrorMessage(buffer, MAX_CFEXP_ERRORMSG);
			AddLogLine(true, GetResString(IDS_ERR_READEMFRIENDS), buffer);
		}
		error->Delete();
		return false;
	}

	return true;
}// MORPH END - Added by Commander, Friendlinks [emulEspaña]
예제 #16
0
파일: MFile.cpp 프로젝트: hozgur/Colorway
BOOL CMFile::FOpen(LPCSTR filename,int opentype)
{
	if (File == NULL) return false;
	if(bDontClose) return false;//bDontClose true ise CFile dýþardan set edilmiþ demektir.
	UINT openflag;
	CFileStatus status;
	if (FileOpen)
	{
		logError("Dosya zaten açýk");
		return false;
	}
	switch (opentype)
	{
	case OT_READ		: openflag = CFile::modeRead |CFile::typeBinary;break;
	case OT_WRITE		: openflag = CFile::modeCreate |CFile::modeWrite|CFile::typeBinary;break;
	case OT_APPEND		: openflag = CFile::modeWrite | CFile::modeNoTruncate|CFile::typeBinary;break;
	case OT_READWRITE	: openflag = CFile::modeReadWrite|CFile::typeBinary;break;		
	default: ASSERT(false);return false;break;
	}
	CFileException e;
	
	if (File->Open(filename,openflag,&e))
	{
		if (File->GetStatus(status))
		{
			ReadOnly = ( (status.m_attribute & 1) != 0);
			Hidden = ( (status.m_attribute & 2) != 0);
			System = ( (status.m_attribute & 4) != 0);
			Archive = ( (status.m_attribute & 0x20) != 0);
			Normal =  status.m_attribute == 0;
			FileOpen = true;
			OpenType = opentype;
			if (opentype == OT_APPEND) 
				File->SeekToEnd();
			return true;
		}
		else
		{
			CString temp;
			temp.Format("(%s)Could not read File Status. Process Terminated.",filename);
			logError(temp);
			return false;
		}
	}
	else
	{		
		char error[200];
		e.GetErrorMessage(error,200);
		logError(error);		
		return false;
	}
		
}
예제 #17
0
void CKmlDlg::convert_all_file()
{
	int i;
	CString temp;
	CKmlDlg::kmlDlg->PostMessage(UWM_PROGRESS, 1, 0);	//Show progress
	for(i = 0; i < NumOfFile; ++i)
	{
		CFileException ef;
		CFile f;
		try
		{
      if(KML_USE_CHECKLISTBOX)
      {
        m_fileList.SetCurSel(i);
      }

			if(!f.Open(FilePath[i], CFile::modeRead,&ef))
			{
				ef.ReportError();
				continue;
			}

			kml_filename = FilePath[i];
			int find = kml_filename.ReverseFind('.');
			kml_filename = kml_filename.Mid(0,find);   

			//Convert(f);
			Convert2(f);
			f.Close();

			temp.Format("%s OK", FileName[i]);
      if(KML_USE_CHECKLISTBOX)
      {
        //m_fileList.SetCurSel(i);
        m_fileList.DeleteString(i);
        m_fileList.InsertString(i, temp);
        m_fileList.SetCheck(i, BST_CHECKED);
      }
      else
      {
			  m_check[i].SetWindowText(temp);
			  m_check[i].SetCheck(BST_CHECKED);	
      }
		}
		catch(CFileException *fe)
		{
			fe->ReportError();
			fe->Delete();
		}	
	}
	CKmlDlg::kmlDlg->PostMessage(UWM_PROGRESS, 0, 1000);	//Hide progress
}
예제 #18
0
파일: Driver.cpp 프로젝트: uesoft/AutoPFA
BOOL Driver::Open(LPCTSTR filename,CStdioFile &File,UINT nOpenFlags)
{
	CFileException ex;
    if (!File.Open(filename,nOpenFlags))
    {
        ex.ReportError();
        return FALSE;
    }
	else
	{
		return TRUE;
	}
}
예제 #19
0
//************************************
// Method:    Open
// FullName:  CRawFileExporter::Open
// Access:    public 
// Returns:   int
// Qualifier:
// Parameter: CString in_szFilePath
//************************************
int CRawFileExporter::Open( CString in_szFilePath )
{
	int ret = SV_NORMAL;
	m_szFilePath = in_szFilePath;
	CFileException ex;
	BOOL bflagOpen = m_oFile.Open(m_szFilePath, CFile::modeWrite | CFile::modeCreate, &ex);
	if(!bflagOpen)
	{
		ret = SV_FILEIO_ERROR;
		ex.ReportError();
		m_szFilePath = _T("");
	}

	return ret;
}
예제 #20
0
//Load EEPROM form a file
//мы заранее знаем размер файла с EEPROM
bool LoadEEPROMFromFile(BYTE* p_data, const std::vector<int>& sizes, int* o_selected_size /*= NULL*/, _TSTRING* o_file_name /*= NULL*/)
{
 HANDLE hFile = 0;
 static TCHAR BASED_CODE szFilter[] = _T("BIN Files (*.bin)|*.bin|All Files (*.*)|*.*||");
 CFileDialog open(TRUE,NULL,NULL,NULL,szFilter,NULL);
 CString cs;

 if (sizes.empty())
  return false; //error, at least one size must be specified
 std::vector<int>::const_iterator p_size_max = std::max_element(sizes.begin(), sizes.end());

 if (open.DoModal()==IDOK)
 {
  CFile f;
  CFileException ex;
  TCHAR szError[1024];
  if(!f.Open(open.GetPathName(), CFile::modeRead, &ex))
  {
   ex.GetErrorMessage(szError, 1024);
   AfxMessageBox(szError);
   return false; //error, can't open file
  }

  //Проверка на размер файла (его размер должен соответствовать одному из разрешенных размеров EEPROM)
  std::vector<int>::const_iterator p_size = std::find(sizes.begin(), sizes.end(), f.GetLength());
  if (p_size==sizes.end())
  {
   AfxMessageBox(GenMessage()(sizes, IDS_FW_WRONG_EE_FILE_SIZE));
   f.Close();
   return false; //ошибка
  }

  f.Read(p_data, *p_size);
  f.Close();

  if (NULL != o_selected_size)
   *o_selected_size = *p_size; //save selected size

  if (NULL != o_file_name)
   *o_file_name = open.GetFileName();

  return true; //подтверждение пользователя
 }
 else
  return false; //отказ пользователя
}
예제 #21
0
파일: Picture.cpp 프로젝트: dulton/brpj
//-----------------------------------------------------------------------------
// Does:   Open a File And Load It Into IPicture (Interface)
// ~~~~    (.BMP .DIB .EMF .GIF .ICO .JPG .WMF)
//
// InPut:  sFilePathName - Path And FileName Target To Save
// ~~~~~   
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicture_Ex::Load(CString sFilePathName)
//=============================================================================
{
 //if(!PathFileExists(sFilePathName))return FALSE;
/*
			CFile file;
			if (!file.Open(sFilePathName, CFile::modeRead/ *|CFile::shareDenyWrite* /))
				return FALSE;*/
		
		
 BOOL bResult = FALSE;
 CFile PictureFile;
 CFileException e;
 int nSize = 0;



 if(m_pPict != NULL) UnloadPicture(); // Important - Avoid Leaks...



 if(PictureFile.Open(sFilePathName, CFile::modeRead | CFile::typeBinary, &e))
  {
  nSize = PictureFile.GetLength();
  BYTE* pBuffer = new BYTE[nSize];
 
  if(PictureFile.Read(pBuffer, nSize) > 0)
   {
   if(LoadPictureData(pBuffer, nSize)) bResult = TRUE;
   }



  PictureFile.Close();
  delete [] pBuffer;
  }
 else // Open Failed...
  {
  TCHAR szCause[255];
  e.GetErrorMessage(szCause, 255, NULL);
  HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
  MessageBoxEx(hWnd, szCause, "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
  bResult = FALSE;
  }
 return(bResult);
}
예제 #22
0
BOOL CImportFile::Load(const TCHAR *filename)
{
	ASSERT( m_pDesign == NULL );

	CFile f;
	CFileException e;
	if( !f.Open( filename, CFile::modeRead, &e ) ) 
	{
		e.ReportError();
		return FALSE;
	}
	CArchive ar( &f, CArchive::load );
	m_pDesign = new CTinyCadMultiDoc;
	m_pDesign->Serialize( ar );

	return TRUE;
}
예제 #23
0
bool CFriendList::LoadList(){
	CString strFileName = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + EMFRIENDS_MET_FILENAME;
	CSafeBufferedFile file;
	CFileException fexp;
	if (!file.Open(strFileName, CFile::modeRead | CFile::osSequentialScan | CFile::typeBinary | CFile::shareDenyWrite, &fexp)){
		if (fexp.m_cause != CFileException::fileNotFound){
			CString strError(GetResString(IDS_ERR_READEMFRIENDS));
			TCHAR szError[MAX_CFEXP_ERRORMSG];
			if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
				strError += _T(" - ");
				strError += szError;
			}
			LogError(LOG_STATUSBAR, _T("%s"), strError);
		}
		return false;
	}

	try {
		uint8 header = file.ReadUInt8();
		if (header != MET_HEADER){
			file.Close();
			return false;
		}
		UINT nRecordsNumber = file.ReadUInt32();
		for (UINT i = 0; i < nRecordsNumber; i++) {
			CFriend* Record =  new CFriend();
			Record->LoadFromFile(&file);
			m_listFriends.AddTail(Record);
		}
		file.Close();
	}
	catch(CFileException* error){
		if (error->m_cause == CFileException::endOfFile)
			LogError(LOG_STATUSBAR,GetResString(IDS_ERR_EMFRIENDSINVALID));
		else{
			TCHAR buffer[MAX_CFEXP_ERRORMSG];
			error->GetErrorMessage(buffer, ARRSIZE(buffer));
			LogError(LOG_STATUSBAR,GetResString(IDS_ERR_READEMFRIENDS),buffer);
		}
		error->Delete();
		return false;
	}

	return true;
}
예제 #24
0
파일: ZipArchive.cpp 프로젝트: F5000/spree
bool CZipArchive::AddNewFile(LPCTSTR lpszBasePath, LPCTSTR lpszFilePath, int iLevel, unsigned long nBufSize)
{
	if (!nBufSize)
		return false;
		
	CFileHeader header;

	if( lpszBasePath )
	{
		header.m_szFileName = GetFileDirAndName(lpszFilePath);
		CString basepath = GetFileDirAndName(lpszBasePath);
		header.m_szFileName.Replace( basepath, _T("") );
	}
	else
	{
		header.m_szFileName = GetFileDirAndName(lpszFilePath);
	}

	if (header.m_szFileName.IsEmpty())
		return false;
	if (!OpenNewFile(header, iLevel, lpszFilePath))
		return false;
	
	if (!IsDirectory(header.m_uExternalAttr))
	{
		CFile f;
		CFileException* e = new CFileException;
		BOOL bRet = f.Open(lpszFilePath, CFile::modeRead | CFile::shareDenyWrite, e);
		e->Delete();
		if (!bRet)
			return false;
		
		DWORD iRead;
		CAutoBuffer buf(nBufSize);
		do
		{
			iRead = f.Read(buf, nBufSize);
			if (iRead)
				WriteNewFile(buf, iRead);
		}
		while (iRead == buf.GetSize());
	}
	CloseNewFile();
	return true;
}
예제 #25
0
bool CJobList::DoIO(LPCTSTR Path, DWORD FileMode, DWORD ArchiveMode)
{
	CFile	fp;
	CFileException	e;
	if (!fp.Open(Path, FileMode, &e)) {
		e.ReportError();
		return(FALSE);
	}
	TRY {
		CArchive	ar(&fp, ArchiveMode);
		ar.m_strFileName = fp.GetFileName();
		Serialize(ar);
	}
	CATCH(CArchiveException, e)
	{
		e->ReportError();
		return(FALSE);
	}
예제 #26
0
void CTxtFile::errorMsg(CFileException& fx)
{
    //例外處理
    TCHAR buf[255];
    fx.GetErrorMessage(buf, 255);
    CString strPrompt;
    strPrompt.Format("CTxtFile說:「%s」", buf);
    AfxMessageBox(strPrompt);
}
예제 #27
0
void COmdFileFactor::ErrorMsg(CFileException& fx) const
{
    //例外處理
    TCHAR buf[255];
    fx.GetErrorMessage(buf, 255);
    CString strPrompt;
    strPrompt.Format("COmdFileFactor::LoadData()\n%s", buf);
    AfxMessageBox(strPrompt);
}
예제 #28
0
void CFriendList::SaveList(){
	if (thePrefs.GetLogFileSaving())
		AddDebugLogLine(false, _T("Saving friends list file \"%s\""), EMFRIENDS_MET_FILENAME);
	m_nLastSaved = ::GetTickCount();

	CString strFileName = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + EMFRIENDS_MET_FILENAME;
	CSafeBufferedFile file;
	CFileException fexp;
	if (!file.Open(strFileName, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary | CFile::shareDenyWrite, &fexp)){
		CString strError(_T("Failed to save ") EMFRIENDS_MET_FILENAME _T(" file"));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		return;
	}
	setvbuf(file.m_pStream, NULL, _IOFBF, 16384);
	
	try{
		file.WriteUInt8(MET_HEADER);
		file.WriteUInt32(m_listFriends.GetCount());
		for (POSITION pos = m_listFriends.GetHeadPosition();pos != 0;)
			m_listFriends.GetNext(pos)->WriteToFile(&file);
		if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning())){
			file.Flush(); // flush file stream buffers to disk buffers
			if (_commit(_fileno(file.m_pStream)) != 0) // commit disk buffers to disk
				AfxThrowFileException(CFileException::hardIO, GetLastError(), file.GetFileName());
		}
		file.Close();
	}
	catch(CFileException* error){
		CString strError(_T("Failed to save ") EMFRIENDS_MET_FILENAME _T(" file"));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (error->GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		error->Delete();
	}
}
예제 #29
0
파일: Patch.cpp 프로젝트: Dewb/UltraWhorld
bool CPatch::Read(LPCTSTR Path)
{
	CStdioFile	fp;
	CFileException	e;
	if (!fp.Open(Path, CFile::modeRead | CFile::shareDenyWrite, &e)) {
		e.ReportError();
		return(FALSE);
	}
	TRY {
		if (!Read(fp)) {
			AfxMessageBox(IDS_DOC_BAD_FORMAT);
			return(FALSE);
		}
	}
	CATCH(CFileException, e)
	{
		e->ReportError();
		return(FALSE);
	}
bool CTestArchivePlugIn::ReadTestArchive( const wchar_t* filename )
{
  if( 0 == filename || 0 == filename[0] )
    return false;

  ON_wString path = filename;
  PathRenameExtension( path.Array(), L".dat" );

  if( !PathFileExists(path) )
  {
    //RhinoApp().Print( L"Error reading test archive - File not found.\n" );
    return false;
  }

  CFile f;
  CFileException e;
  if( !f.Open(path, CFile::modeRead, &e) )
  {
    wchar_t msg[255];
  	memset( msg, 0, sizeof(wchar_t) * 255);
    e.GetErrorMessage( msg, 255 );
    RhinoApp().Print( L"Error reading test archive - %s\n", msg );
    return false;
  }

  try
  {
    CArchive ar( &f, CArchive::load );
    m_list.Serialize( ar );
    ar.Close();
    f.Close();
  }
  catch( CFileException* ex )
  {
    wchar_t msg[255];
  	memset( msg, 0, sizeof(wchar_t) * 255);
    ex->GetErrorMessage( msg, 255 );
    RhinoApp().Print( L"Error reading test archive - %s\n", msg );
    ex->Delete();
  }

  return true;
}