コード例 #1
0
ファイル: ClientSocket.cpp プロジェクト: isongbo/MyCode
BOOL CClientSocket::SendFile(CString strPath)
{
	// 发送文件
	// 1 打开文件,获取文件信息和数据
  CFile file;
	file.Open(strPath,CFile::modeRead);
  
	HEADER header={0};
	header.nLen=file.GetLength();
  strcpy(header.szFile,file.GetFileName());
  
	BYTE* pData=(BYTE*)malloc(header.nLen);
	file.Read(pData,header.nLen);
	file.Close();
	//2 发送文件信息
  if (!SendData((BYTE*)&header,sizeof(header)))
  {
		AfxMessageBox("发送文件信息失败!");
		return FALSE;
  }
	//3 发送文件数据
	if (!SendData(pData,header.nLen))
	{
	  AfxMessageBox("发送文件数据失败!");
		return FALSE;
	}

	//4 释放内存,关闭套接字
	free(pData);
	Close();
	return TRUE;
}
コード例 #2
0
ファイル: ChatDlg.cpp プロジェクト: yzr0512/ChatClient
/*********************************************************
函数名称:OnBnClickedButtonSendFile
功能描述:发送传送文件请求
作者:	  余志荣
创建时间:2016-08-29
参数说明:
返 回 值:
*********************************************************/
void CChatDlg::OnBnClickedButtonSendFile()
{
	// 构造打开文件对话框
	CFileDialog fileDlg(TRUE); 
	
	CString strFilePath;
	// 显示打开文件对话框
    if (IDOK == fileDlg.DoModal())   
    {   
		strFilePath = fileDlg.GetPathName();// 包含文件路径和文件名
	}
	else
	{
		return;
	}

	CFile file;

	if(!file.Open(strFilePath, CFile::modeRead))
	{
		MessageBox(L"选择文件有误!");
		return;
	}
	CString strFileName;
	strFileName = file.GetFileName(); // 文件名
	//strFilePath = file.GetFilePath(); // 文件路径
	strFilePath = strFilePath.Left(strFilePath.GetLength() - strFileName.GetLength() - 1);

	MSG_FILE_REQUEST msg_file;
	memset(&msg_file, 0, sizeof(MSG_FILE_REQUEST)); // 结构体清空
	// 构造文件发送请求结构体
	msg_file.nType = MESSAGE_FILE_REQUEST;
	strcpy_s(msg_file.ToID, m_nID);	// 对方ID
	CString strMyID = ((CMFCChatDlg*)theApp.m_pMainWnd)->m_csMyID; // 我的ID
	WideCharToMultiByte(CP_ACP, 0, strMyID, strMyID.GetLength() + 1, msg_file.FromID, ID_MAX, NULL, NULL);
	msg_file.nFileID = ((CMFCChatDlg*)theApp.m_pMainWnd)->GetAvailFileID(); // 获得可用的文件ID
	//WideCharToMultiByte(CP_ACP, 0, strFilePath, strFilePath.GetLength() + 1, msg_file.FileName, 512, NULL, NULL);
	WideCharToMultiByte(CP_ACP, 0, strFileName, strFileName.GetLength() + 1, msg_file.FileName, 512, NULL, NULL); // 文件名
	msg_file.nFileSize = file.GetLength(); // 文件大小

	((CMFCChatDlg*)theApp.m_pMainWnd)->SendMsg(&msg_file, sizeof(MSG_FILE_REQUEST)); // 发送消息

	// 本地记录构建
	FILE_RECORD *pFile_record = new FILE_RECORD;
	memset(pFile_record, 0, sizeof(FILE_RECORD));// 结构体清空
	pFile_record->bType = true; // 记录类型 设为 发送
	strcpy_s(pFile_record->ToID, m_nID);	// 对方ID
	strcpy_s(pFile_record->FromID, msg_file.FromID); // 我的ID
	WideCharToMultiByte(CP_ACP, 0, strFilePath, strFilePath.GetLength() + 1, pFile_record->FilePath, 512, NULL, NULL);// 文件路径
	WideCharToMultiByte(CP_ACP, 0, strFileName, strFileName.GetLength() + 1, pFile_record->FileName, 512, NULL, NULL);// 文件名
	pFile_record->nFileID = msg_file.nFileID; // 文件ID
	pFile_record->nFileSize = file.GetLength(); // 文件大小
	
	((CMFCChatDlg*)theApp.m_pMainWnd)->m_FileRecordList.AddTail(pFile_record); // 将记录添加到链表中
	
	file.Close(); // 关闭文件
}
コード例 #3
0
/////////////////////////////////////////////////////////////////////////////
// CDialConfigDec message handlers
BOOL CDialConfigDec::OnInitDialog() 
{
	CDialog::OnInitDialog();
	

	CFile Test;
	BYTE compnbpar;

	if(Test.Open(NomFichPMC,CFile::modeRead))
	{
		Test.Read(&NBclass,1);
		Test.Read(&NBpar,1);
		m_pmc.SetWindowText(Test.GetFileName());
		ValidPMC=TRUE;
		Test.Close();
	
		if(Test.Open(NomFichParam,CFile::modeRead))
		{
			Test.Read(&compnbpar,1);
			if(compnbpar!=NBpar)
			{
				MessageBox("Fichier  "+Test.GetFileName()+"  incompatible!","Nombre de paramètres",MB_OK|MB_ICONSTOP);
				Test.Close();
			}
			else
			{
				m_param.SetWindowText(Test.GetFileName());
				ValidPARAM=TRUE;
				Test.Close();
			}
		}
	}
	m_ok.EnableWindow(ValidPMC&&ValidPARAM);
	m_param.EnableWindow(ValidPMC);
	m_edit1.EnableWindow(m_check);
	m_spin.EnableWindow(m_check);
	m_checkbox.EnableWindow(ValidPMC&&ValidPARAM);
	m_spin.SetRange(0,NBclass-1);
	m_spin.SetPos(m_classeaffect);
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
コード例 #4
0
// Special handling of OnSetFocus and OnSize are required for a container
//  when an object is being edited in-place.
void CGenEdView::OnSetFocus(CWnd* pOldWnd)
{
    // inform var selection from doc change
    CMainFrame* pMainFrame = NULL;
    pMainFrame = dynamic_cast<CMainFrame* > (AfxGetMainWnd ());
    if (pMainFrame == NULL)
    {
        return;
    }

    CPouVarSelWindow* pVarSelWin = pMainFrame->GetPouVarSel(false);
    if (pVarSelWin)
    {
        CPouVarSelCtrlWrapper* pVarSelWrapper = pVarSelWin->GetWrapper();
        if (pVarSelWrapper)
        {
            CGenEdDoc* pDoc = GetDocument();
            if (pDoc)
            {
                CString strPouName = pDoc->GetDocumentFile();
                CFile file;
                file.SetFilePath(strPouName);
                strPouName = file.GetFileName();
				CCEMAINApp* pApp = (CCEMAINApp*)AfxGetApp();
				if(!pApp->IsOpeningProject())
				{
					pVarSelWrapper->SetVarSelectionHint(strPouName, _T(""), _T(""));
				}
            }
        }
    }



//    if(m_pDocument)
//    {
//	    COleClientItem* pActiveItem = GetDocument()->GetInPlaceActiveItem(this);
//	    if (pActiveItem != NULL &&
//		    pActiveItem->GetItemState() == COleClientItem::activeUIState)
//	    {
//		    // need to set focus to this item if it is in the same view
//		    CWnd* pWnd = pActiveItem->GetInPlaceWindow();
//		    if (pWnd != NULL)
//		    {
//                SetFocusToServer ();
//			    return;
//		    }
//	    }
//    }

	CView::OnSetFocus(pOldWnd);

   
}
コード例 #5
0
ファイル: Torrent.cpp プロジェクト: supertanglang/NeoLoader
QString	CTorrent::GetSubFilePath(int Index)
{
    const QList<CTorrentInfo::SFileInfo>& Files = m_TorrentInfo->GetFiles();
    if(Files.size() <= Index)
        return "";
    CFile * pFile = GetFile();

    QString Dir = pFile->GetFileDir();
    Dir += pFile->GetFileName() + "/";
    if(!Files[Index].FilePath.isEmpty())
        Dir += Files[Index].FilePath.join("/") + "/";

    return Dir;
}
コード例 #6
0
void CDialConfigDec::OnButton2() 
{
	CFile Fichier; // variable fichier 	                                        
	BYTE compnbpar;
	CFileDialog * FileData = new CFileDialog (TRUE,"*.param",NomFichParam,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"Paramètres (*.param)|*.param|",this);

	if (FileData->DoModal()==IDOK)
	{
		if(FileData->GetFileExt()!="param")
		{
			MessageBox("Le fichier selectionné n'est pas valide!","Erreur",MB_OK|MB_ICONSTOP);
			m_pmc.SetWindowText("*.param");
			ValidPARAM=FALSE;
		}
		else if (Fichier.Open(FileData->GetPathName(), CFile::modeRead))
		{ 
			Fichier.Read(&compnbpar,1);

			if(compnbpar!=NBpar)
			{
				MessageBox("Fichier  "+Fichier.GetFileName()+"  incompatible!","Nombre de paramètres",MB_OK|MB_ICONSTOP);
				m_param.SetWindowText("*.param");
				ValidPARAM=FALSE;
				Fichier.Close(); 
			}
			else
			{
				NomFichParam=FileData->GetPathName();
				m_param.SetWindowText(FileData->GetFileName());
				ValidPARAM=TRUE;
				Fichier.Close();
			}
		}
		else 
		{
			MessageBox("Le fichier  "+FileData->GetFileName()+"  n'existe pas!","Erreur",MB_OK|MB_ICONSTOP);
			ValidPARAM=FALSE;
		}
	}

	m_ok.EnableWindow(ValidPARAM&&ValidPMC);
	m_checkbox.EnableWindow(ValidPARAM&&ValidPMC);
	m_param.EnableWindow(ValidPMC);
	UpdateData(FALSE);
	delete FileData;
}
コード例 #7
0
ファイル: JobList.cpp プロジェクト: victimofleisure/FFRend
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);
	}
コード例 #8
0
ファイル: Shortcut.cpp プロジェクト: ByteRisc/pwsafe
BOOL CShortcut::DeleteShortCut(const CString &LnkName, UINT SpecialFolder)
{
  CFile cfFull;
  CString sExePath, sExe, sSpecialFolder;
  wchar_t *chTmp = sExePath.GetBuffer(MAX_PATH);

  GetModuleFileName(NULL, chTmp, MAX_PATH);
  sExePath.ReleaseBuffer();

  if (!GetSpecialFolder(SpecialFolder, sSpecialFolder))
    return FALSE;

  // Work with the special folder's path (contained in szPath)
  cfFull.SetFilePath(sExePath);
  sExe = cfFull.GetFileName();
  sExe.Delete(sExe.Find(L".") + 1, 3);
  sSpecialFolder += LnkName + L"." + L"lnk";

  // DELETE THE LINK:
  SHFILEOPSTRUCT FIO = {0};
  //  FIO.pTo=NULL; // MUST be NULL
  FIO.wFunc = FO_DELETE;
  FIO.fFlags = FOF_NOERRORUI | FOF_NOCONFIRMATION;

  if (sSpecialFolder.Find(L'\0') != sSpecialFolder.GetLength()) {
    FIO.fFlags |= FOF_MULTIDESTFILES;
  }

  if (sSpecialFolder.Right(1)) {
    sSpecialFolder += L'\0';
  }

  FIO.pFrom = &*sSpecialFolder;

  int bD = SHFileOperation(&FIO);

  if (!bD) {
    pws_os::Trace(L"Lnk Deleted!\n");
    return TRUE;
  } else {
    pws_os::Trace(L"Lnk NOT Deleted! DeleteShortCut(...) FAILED!\n");
    return FALSE;
  }
}
コード例 #9
0
ファイル: stdemdef.cpp プロジェクト: test2zhou/MyIM
BOOL EM_FILEINFO::AddFile(LPCTSTR lpszFileFullName, LPCTSTR lpszFileExt)
{
	ASSERT(lpszFileFullName != NULL);

	CFile file;
	BOOL bResult = file.Open(lpszFileFullName, CFile::modeRead|CFile::shareDenyNone, NULL);
	if(!bResult)
	{
		EM_Error("EM_FILEINFO::AddFile could not open file.", GetLastError());
		return FALSE;
	}
	dwSize = file.GetLength();
	strcpy(szName, (LPCTSTR)file.GetFileName());

	strcpy(szFullName, lpszFileFullName);
	strcpy(szExt, lpszFileExt);

	// 关闭文件
	file.Close();

	return bResult;
}
コード例 #10
0
ファイル: RankDlg.cpp プロジェクト: astroluj/MFC
// 초기화 버튼 클릭
void CRankDlg::OnBnClickedButtonDelall()
{
	// 우선 리스트 컨트롤에 있는 값을 비우고, 
	// 해당 리스트 컨트롤의 데이터가 있는 file의 이름을 얻은 다음
	// 해당 파일을 초기화 한다.
	rankList.DeleteAllItems () ;	
	FILE *fp;
	CFile file (rankName, 
		CFile::shareDenyNone 
		| CFile ::modeCreate 
		| CFile ::modeNoTruncate 
		| CFile ::modeRead) ;	
	strLev = file.GetFileName();

	// 파일 내용 초기화
	if(strLev == _T("EasyRanking.txt"))
		fp = fopen("c:\\image\\EasyRanking.txt",  "w");
	else if(strLev == _T("NormalRanking.txt"))
		fp = fopen("c:\\image\\NormalRanking.txt",  "w");
	else 
		fp = fopen("c:\\image\\HardRanking.txt",  "w");
}
コード例 #11
0
ファイル: Torrent.cpp プロジェクト: supertanglang/NeoLoader
bool CTorrent::MakeTorrent(uint64 uPieceLength, bool bMerkle, const QString& Name, bool bPrivate)
{
    CFile* pFile = GetFile();

    if(!pFile->IsComplete())
    {
        LogLine(LOG_DEBUG | LOG_ERROR, tr("A torrent can not be made form an Incompelte file %1").arg(pFile->GetFileName()));
        return false;
    }

    if(uPieceLength < KB2B(16)) //if(!uPieceLength)
    {
        uPieceLength = pFile->GetFileSize() / (KB2B(40) / 20); // target hast set size 40 KB

        uint64 i = KB2B(16);
        for (; i < MB2B(32); i *= 2)
        {
            if (i >= uPieceLength)
                break;
        }
        uPieceLength = i;
    }

    m_TorrentInfo = new CTorrentInfo(this);
    m_TorrentInfo->SetTorrentName(Name.isEmpty() ? pFile->GetFileName() : Name);
    m_TorrentInfo->SetTotalLength(pFile->GetFileSize());
    if(bPrivate)
        m_TorrentInfo->SetPrivate();

    m_TorrentInfo->SetProperty("CreationTime", QDateTime::currentDateTime());

    ASSERT(m_pHash.isNull());
    if(bMerkle)
        m_pHash = CFileHashPtr(new CFileHashTree(HashTorrent, m_TorrentInfo->GetTotalLength(), uPieceLength));
    else
        m_pHash = CFileHashPtr(new CFileHashSet(HashTorrent, m_TorrentInfo->GetTotalLength(), uPieceLength));
    return true;
}
コード例 #12
0
BOOL CHttpUploadFileProc::UseHttpSendReqEx(HINTERNET hRequest, CFile &file)
{
    //	生成form-data协议信息	<begin>
    CStringA	straHeader;
    CStringA	straContentHead;
    CStringA	straContentTail;

    straHeader = GetHttpAppendHeader();
    straContentHead = GetContentHead(file.GetFileName());
    straContentTail = GetContentTail();
    //	生成form-data协议信息	<end>

    ULONGLONG	ullFileLength = file.GetLength();
    DWORD	dwContentLength = straContentHead.GetLength() + (DWORD) ullFileLength + straContentTail.GetLength();

    INTERNET_BUFFERS BufferIn = {0};
    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL;
    //BufferIn.lpcszHeader = NULL;
    //BufferIn.dwHeadersLength = 0;
    BufferIn.lpcszHeader = straHeader.LockBuffer();
    straHeader.UnlockBuffer();
    BufferIn.dwHeadersLength = (DWORD)straHeader.GetLength();
    BufferIn.dwHeadersTotal = 0;
    BufferIn.lpvBuffer = NULL;
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = dwContentLength;
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_SENDING_FILE, 0);
    if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
        return FALSE;

    UINT	uProgressBegin = 10;
    UINT	uProgressEnd = 90;
    UINT	uProgressCur = 0;
    UINT	uReadCountSum = 0;


    const UINT uBufSize = 1024;
    BYTE pBuffer[uBufSize];
    UINT uReadCount;
    DWORD dwBytesWritten;
    BOOL bRet;
    float	fSendPercent;
    UINT	uProgressScale;


    //	Write Head
    bRet = InternetWriteFile( hRequest, straContentHead.LockBuffer(), straContentHead.GetLength(), &dwBytesWritten);
    straContentHead.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }

    if (IsTerminated())	return FALSE;
    //	Write file contents
    uReadCountSum = 0;
    bRet = TRUE;
    file.SeekToBegin();
    do {
        if (IsTerminated())	return FALSE;
        uReadCount = file.Read(pBuffer, uBufSize);
        if (0 == uReadCount)
            break;

        if(! InternetWriteFile( hRequest, pBuffer, uReadCount, &dwBytesWritten))
        {
            NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
            return FALSE;
        }

        uReadCountSum += uReadCount;
        fSendPercent = (float)uReadCountSum / BufferIn.dwBufferTotal;
        uProgressScale = (UINT) ((uProgressEnd - uProgressBegin) * fSendPercent);
        uProgressCur = uProgressBegin + uProgressScale;
        NotifyReceiver(P_HUF_PROGRESS, uProgressCur);

    } while (uReadCount == uBufSize);

    if (IsTerminated())	return FALSE;
    //	Write Tail
    bRet = InternetWriteFile( hRequest, straContentTail.LockBuffer(), straContentTail.GetLength(), &dwBytesWritten);
    straContentTail.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }
    NotifyReceiver(P_HUF_PROGRESS, uProgressEnd);


    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_WAIT_RESPONSE, 0);
    if (!HttpEndRequest(hRequest, NULL, 0, 0))
    {
        NotifyReceiver(E_HUF_WAIT_RESPONSE_FAILD, 0);
        bRet = FALSE;
    }

    return bRet;
}
コード例 #13
0
ファイル: Torrent.cpp プロジェクト: supertanglang/NeoLoader
void CTorrent::SetupPartMap()
{
    ASSERT(!m_TorrentInfo->IsEmpty());

    CFile* pFile = GetFile();

    // Single File
    if(!m_TorrentInfo->IsMultiFile())
    {
        if(!pFile->GetPartMap())
            pFile->SetPartMap(CPartMapPtr(new CSynced<CPartMap>(m_TorrentInfo->GetTotalLength())));
        return;
    }

    // Multi File:

    CJoinedPartMap* pParts = qobject_cast<CJoinedPartMap*>(pFile->GetPartMap());
    if(pParts)
    {
        ASSERT(!pParts->GetLinks().isEmpty());
        return; // is already set up
    }
    pParts = new CJoinedPartMap(pFile->GetFileSize());

    pFile->GetInspector()->SetIndexSource(HashTorrent);

    CFileList* pList = pFile->GetList();

    uint64 Offset = 0;
    foreach(const CTorrentInfo::SFileInfo& SubFile, m_TorrentInfo->GetFiles())
    {
        if(SubFile.Length == 0)
        {
            LogLine(LOG_DEBUG | LOG_WARNING, tr("Ignoring empty file '%1' in torrent '%2'").arg(SubFile.FileName).arg(pFile->GetFileName()));
            continue;
        }

        CFile* pSubFile = new CFile();
        if(pFile->GetProperty("Temp").toBool())
            pSubFile->SetProperty("Temp", true);

        QString Dir = pFile->GetFileDir();
        Dir += pFile->GetFileName() + "/";
        if(!SubFile.FilePath.isEmpty())
            Dir += SubFile.FilePath.join("/") + "/";
        pSubFile->SetFileDir(Dir);

        pSubFile->AddEmpty(HashTorrent, SubFile.FileName, SubFile.Length, pFile->IsPending());

        // Note: SubFile->MasterHash is set in MasterFile->Resume

        uint64 uBegin = Offset;
        uint64 uEnd = Offset + SubFile.Length;
        Offset += SubFile.Length;

        CSharedPartMap* pSubParts = new CSharedPartMap(uEnd - uBegin);
        pSubFile->SetPartMap(CPartMapPtr(pSubParts));

        pParts->SetupLink(uBegin, uEnd, pSubFile->GetFileID());
        pSubParts->SetupLink(uBegin, uEnd, pFile->GetFileID());

        pList->AddFile(pSubFile);

        if(!pSubFile->IsPending())
            pSubFile->Resume();

        if(pFile->IsPaused(true))
            pSubFile->Pause();
        else if(pFile->IsStarted())
            pSubFile->Start();
    }

    pFile->SetPartMap(CPartMapPtr(pParts));
}
コード例 #14
0
ファイル: Torrent.cpp プロジェクト: supertanglang/NeoLoader
bool CTorrent::LoadTorrentFromFile(const QByteArray& InfoHash)
{
    ASSERT(m_TorrentInfo == NULL);
    m_TorrentInfo = new CTorrentInfo(this);

    ASSERT(m_pHash.isNull());
    m_pHash = CFileHashPtr(new CFileHash(HashTorrent));
    m_pHash->SetHash(InfoHash);

    QString TorrentFile = QString(InfoHash.toHex()) + ".torrent";

    if(m_TorrentInfo->LoadTorrentFile(theCore->m_TorrentManager->GetTorrentDir() + TorrentFile))
    {
        if(m_TorrentInfo->GetInfoHash() == InfoHash)
        {
            CFile* pFile = GetFile();

            if(pFile->GetFileSize() == 0)
                pFile->SetFileSize(m_TorrentInfo->GetTotalLength());

            LoadPieceHashes();

            if(m_TorrentInfo->IsMultiFile() && !pFile->IsMultiFile())
            {
                CFileHashPtr pMasterHash = pFile->GetMasterHash();
                if(!pMasterHash.isNull() && pMasterHash->GetHash() == InfoHash)
                {
                    LogLine(LOG_DEBUG | LOG_ERROR, tr("The multi file %1 is missing its proper index, restoring form torrent").arg(pFile->GetFileName()));
                    InstallMetadata();
                }
            }

            if(!m_TorrentInfo->IsEmpty() && !pFile->IsComplete() && !pFile->GetPartMap())
                SetupPartMap();
        }
        else
        {
            LogLine(LOG_DEBUG | LOG_ERROR, tr("The torrent file %1 contains an invalid infohash").arg(TorrentFile));
            delete m_TorrentInfo;
            m_TorrentInfo = new CTorrentInfo(this);
            m_TorrentInfo->SetInfoHash(InfoHash);
        }
    }
    else
        m_TorrentInfo->SetInfoHash(InfoHash);
    theCore->m_TorrentManager->RegisterInfoHash(m_TorrentInfo->GetInfoHash());

    return true; // Note: that is always true even if we fail to load as we always wil be able to proceed one way or another
}
コード例 #15
0
ファイル: Torrent.cpp プロジェクト: supertanglang/NeoLoader
void CTorrent::OnFileHashed()
{
    CFile* pFile = GetFile();
    ASSERT(m_TorrentInfo);
    if(m_TorrentInfo->IsEmpty()) // are we making a torrent
    {
        QStringList Shared = theCore->Cfg()->GetStringList("Content/Shared");
        Shared.append(theCore->GetIncomingDir());
        Shared.append(theCore->GetTempDir());

        QList<CTorrentInfo::SFileInfo> Files;
        if(CJoinedPartMap* pParts = qobject_cast<CJoinedPartMap*>(pFile->GetPartMap()))
        {
            QMap<uint64, SPartMapLink*> Links = pParts->GetJoints();
            for(QMap<uint64, SPartMapLink*>::iterator I = Links.end(); I != Links.begin();)
            {
                SPartMapLink* pLink = *(--I);

                CFile* pSubFile = pFile->GetList()->GetFileByID(pLink->ID);
                if(!pSubFile)
                {
                    LogLine(LOG_DEBUG | LOG_ERROR, tr("A sub file of %1 has been being removed befoure the torrent was created").arg(pFile->GetFileName()));
                    pFile->TorrentHashed(this, false);
                    return;
                }

                CTorrentInfo::SFileInfo File;
                QString Root;
                QStringList Path = GetRelativeSharedPath(pSubFile->GetFilePath(), Shared, Root).split("/", QString::SkipEmptyParts);
                if(!Path.isEmpty())
                {
                    if(Path.count() > 1)
                        Path.removeFirst();
                    File.FileName = Path.takeLast();
                    File.FilePath = Path;
                }
                else
                    File.FileName = "unknown";
                File.Length = pSubFile->GetFileSize();
                Files.append(File);
            }
        }

        if(CFileHashTree* pHashTree = qobject_cast<CFileHashTree*>(m_pHash.data()))
            m_TorrentInfo->MakeMetadata(Files, pHashTree->GetPartSize(), QList<QByteArray>(), pHashTree->GetRootHash());
        else if(CFileHashSet* pHashSet = qobject_cast<CFileHashSet*>(m_pHash.data()))
            m_TorrentInfo->MakeMetadata(Files, pHashSet->GetPartSize(), pHashSet->GetHashSet());
        else {
            ASSERT(0);
        }

        if(!pFile->IsPending())
            SaveTorrentToFile();

        m_pHash->SetHash(m_TorrentInfo->GetInfoHash());
        theCore->m_TorrentManager->RegisterInfoHash(m_TorrentInfo->GetInfoHash());

        pFile->TorrentHashed(this, true);
    }
    else // we are importing a torrent
    {
        bool bMatch = false;

        if(CFileHashTree* pHashTree = qobject_cast<CFileHashTree*>(m_pHash.data()))
            bMatch = m_TorrentInfo->GetRootHash() == pHashTree->GetRootHash();
        else if(CFileHashSet* pHashSet = qobject_cast<CFileHashSet*>(m_pHash.data()))
            bMatch = m_TorrentInfo->GetPieceHashes() == pHashSet->GetHashSet();
        else {
            ASSERT(0);
        }

        if(bMatch)
        {
            if(!pFile->IsPending())
                SaveTorrentToFile();

            m_pHash->SetHash(m_TorrentInfo->GetInfoHash());
            theCore->m_TorrentManager->RegisterInfoHash(m_TorrentInfo->GetInfoHash());
        }

        pFile->TorrentHashed(this, bMatch);
    }
}
コード例 #16
0
ファイル: NtMagickView.cpp プロジェクト: ImageMagick/contrib
void CNtMagickView::OnFileOpen()

{

  CString   szFolder;

  CString   szFilter;

  szFilter += NTMAGICK_JPEG;

  szFilter += NTMAGICK_BMP;

  szFilter += NTMAGICK_GIF;

  szFilter += NTMAGICK_TIF;

  szFilter += NTMAGICK_ICON;

  szFilter += NTMAGICK_ALL;

  szFilter += "|";



  szFolder = AfxGetApp()->GetProfileString(L"Image",L"Path",L"");



  CFileDialog fileDlg(TRUE,NULL,NULL,NULL,szFilter,NULL);

  fileDlg.m_ofn.Flags|=OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_READONLY;

  fileDlg.m_ofn.lpstrTitle=L"Choose the image to view";

  fileDlg.m_ofn.lpstrInitialDir= szFolder;



  if (fileDlg.DoModal()== IDOK)

  {

    m_szFile = fileDlg.GetPathName();

    if (DoReadImage())

    {

      DoDisplayImage();



      CFile     fileImage;



      fileImage.SetFilePath(m_szFile);

      szFolder = m_szFile;

      szFolder.TrimRight(fileImage.GetFileName());

      szFolder.TrimRight(L"\\");

      AfxGetApp()->WriteProfileString(L"Image",L"Path", szFolder);

    }

  }

}
コード例 #17
0
ファイル: Shortcut.cpp プロジェクト: ByteRisc/pwsafe
BOOL CShortcut::CreateShortCut(const CString &LnkTarget,
                               const CString &LnkName, UINT SpecialFolder,
                               const CString &LnkDescription,
                               const CString &IconLocation, UINT IconIndex)
{
  CFile cfFull;
  CString sExePath, sExe, sSpecialFolder;

  wchar_t *chTmp = sExePath.GetBuffer(MAX_PATH);

  GetModuleFileName(NULL, chTmp, MAX_PATH);

  sExePath.ReleaseBuffer();

  // Find the Special Folder:
  if (!GetSpecialFolder(SpecialFolder, sSpecialFolder))
    return FALSE;

  sSpecialFolder += LnkName + L"." + L"lnk";

  if (LnkTarget == L"_this") {
    cfFull.SetFilePath(sExePath);
    sExe = cfFull.GetFileName();
    sExe.Delete(sExe.Find(L".") + 1, 3);
  } else {
    sExePath = LnkTarget;
  }

  // Create the ShortCut:
  CoInitialize(NULL);
  BOOL bRet = FALSE;
  IShellLink* psl;

  if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink,
                                 NULL,
                                 CLSCTX_INPROC_SERVER,
                                 IID_IShellLink,
                                 (LPVOID*) &psl))) {
    IPersistFile* ppf;

    psl->SetPath(sExePath);
    psl->SetDescription(LnkDescription);

    if (!m_sCmdArg.IsEmpty())
      psl->SetArguments(m_sCmdArg);

    if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) {
      /* Call IShellLink::SetIconLocation with the file containing
         the icon and the index of the icon */
      if (!IconLocation.IsEmpty()) {
        HRESULT hr = psl->SetIconLocation(IconLocation, IconIndex);
#ifdef _DEBUG
        if (FAILED(hr))
          pws_os::Trace(L"IconLocation not changed!\n");
#endif
      }

      if (SUCCEEDED(ppf->Save(sSpecialFolder, TRUE)))
      {
        bRet = TRUE;
      }
      ppf->Release();
    }
    psl->Release();
  } 

  pws_os::Trace(bRet ? L"Lnk Written!\n" :
               L"Lnk NOT Written! CreateShortCut(...) failed!\n");
  return bRet;
}
コード例 #18
0
ファイル: GlobalFun.cpp プロジェクト: uvbs/myhistoryprojects
FileState SendFile(SOCKET socket, HWND hWrapperWnd, LPCTSTR strFilePathName, ULONGLONG llStartAt)
{
	//gl_SenderStop = false;
	gl_mapSenderStop[hWrapperWnd] = false;
	PostMessage(hWrapperWnd, WM_FILE_OPERATE_BEGIN, 1, 0);

	FileState MyFileState = S_FileOK, YouFileState = S_FileOK;

	//check dir
	CString strFileName = strFilePathName;
	CDestFolderHelper folderHelper;
	if (!folderHelper.IsDestFileExist(strFileName))
		MyFileState = S_FileNotExits;

	//open file
	CFile LocalFile;
	if(!LocalFile.Open(strFileName, CFile::modeRead | CFile::typeBinary))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_OpenFileFailed;
	}

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

	//get file time
	FILETIME fileTime;
	if(!GetFileTime(LocalFile.m_hFile, NULL, NULL, &fileTime))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_GetFileInfoFailed;
	}

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

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

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

	//init basicFileInfo
	BasicFileInfo basicFileInfo;
	basicFileInfo.CreationTime = fileTime;
	char* pFileName = (LPSTR)(LPCTSTR)(LocalFile.GetFileName());
	memset(&(basicFileInfo.FileName), 0, MAX_PATH);
	CopyMemory(&(basicFileInfo.FileName), pFileName, LocalFile.GetFileName().GetLength());
	basicFileInfo.Size = LocalFile.GetLength();

	//send file info
	if (!SendData(socket, (char*)(&basicFileInfo), sizeof(basicFileInfo)))
	{
		LocalFile.Close();
		return S_SocketError;
	}
	ULONGLONG nDes = LocalFile.GetLength() > 1024 * 1024 * 1024 ? 1024 * 1024 : 1024;	//file's size larger than 1G.
	PostMessage(hWrapperWnd, WM_FILE_SETRANGE_MESSAGE, (WPARAM)(LocalFile.GetLength() / nDes), (LPARAM)0);

	ULONGLONG nRead = llStartAt;
	ULONGLONG nResCount = 0;
	ULONGLONG nFileLength = LocalFile.GetLength();
	FileDataEx fileData;
	
	PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nRead / nDes), 0);
	if (gl_pLogger) gl_pLogger->log_info("SendFile Begin to send: %s", strFilePathName);

	bool *pbstatus = NULL;
	SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&pbstatus);
	//send loop
	while(1)
	{
		int nCount = 0;
		try{
			nCount= LocalFile.Read(fileData.data.Buf, FILEDATASIZE);
		}
		catch(...){
			fileData.state = S_ReadFileFailed;
		}
		fileData.data.nLength = nCount;
		nRead += nCount;

		fileData.state = (*pbstatus) ? S_FileContinue : S_IStop;
		if(nRead == nFileLength)
			fileData.state = S_Finished;
		
		//if(gl_SenderStop)
		if (gl_mapSenderStop.find(hWrapperWnd) != gl_mapSenderStop.end() && gl_mapSenderStop[hWrapperWnd] == true)
		{
			fileData.state = S_IStop;
		}		

		if (!SendData(socket, (char*)(&fileData), sizeof(fileData)))
		{
			LocalFile.Close();
			return S_SocketError;
		}

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

		if(fileData.state == S_IStop)// || fileData.state == S_ReadFileFailed
		{
			LocalFile.Close();
			return fileData.state;
		}
		
		if(fileData.state == S_Finished)// || fileData.state == S_ReadFileFailed
		{
			LocalFile.Close();
			return fileData.state;
		}

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

			if(fileData.state == S_ReadFileFailed)
				MyState = S_ReadFileFailed;
			else
				MyState = (*pbstatus) ? S_FileContinue : S_IStop;

			if(!SendData(socket, (char*)&MyState, sizeof(FileState)))
			{
				LocalFile.Close();
				return S_SocketError;
			}
			if(!ReceiveData(socket, (char*)&YouState, sizeof(FileState)))
			{
				LocalFile.Close();
				return S_SocketError;
			}
			
			if(YouState == S_WriteFileFailed || YouState == S_IStop)
			{
				LocalFile.Close();
				if (YouState == S_IStop)
					return S_OtherSideStop;
				return YouState;
			}

			if(MyState == S_ReadFileFailed || MyState == S_IStop)
			{
				LocalFile.Close();
				if (MyState == S_IStop)
					return S_IStop;
				return MyState;
			}
		}

		PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nRead / nDes), 0);
	}

	return S_Finished;
}