// 获取文件基本属性 #if 0 CFile成员: BOOL GetStatus(CFileStatus& rStatus) const; static BOOL PASCAL GetStatus(LPCTSTR lpszFileName,CFileStatus& rStatus,CAtlTransactionManager* pTM = NULL); #endif CFileStatus fileStatus; if (CFile::GetStatus(_T("D:\config.ini"), fileStatus))// 给个目录名也行,如D:\ { TRACE(_T("文件创建时间:%s "), fileStatus.m_ctime.Format(_T("%Y-%m-%d %H:%M:%S"))); TRACE(_T("文件修改时间:%s "), fileStatus.m_mtime.Format(_T("%Y-%m-%d %H:%M:%S"))); TRACE(_T("最后访问时间:%s "), fileStatus.m_atime.Format(_T("%Y-%m-%d %H:%M:%S"))); TRACE(_T("绝对文件名 :%s "), fileStatus.m_szFullName); }
// 选择文件夹 CString folder; CFolderPickerDialog pickerDialog; if (pickerDialog.DoModal() == IDOK) { folder = pickerDialog.GetFolderPath(); TRACE(folder); // Eg: D:dir } else { TRACE(_T("dialog canceled")); }
// 选择文件 std::vector<CString> selectFiles; TCHAR szFilter[] = _T("Text Files(*.txt;*.csv)|*.txt; *.csv|Image Files(*.bmp;*.png;*.jpg;*.raw)|*.bmp; *.png; *.jpg; *.raw|All Files (*.*)|*.*||"); CFileDialog openFileDlg(TRUE, // TRUE表示打开 _T("*.txt"), // 默认文件扩展名 NULL, OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY /*| OFN_ALLOWMULTISELECT 可以开启多选模式*/, szFilter); openFileDlg.m_ofn.lpstrTitle = _T("选择图片文件或文本文件");// 可以设置对话框的标题 if (IDOK == openFileDlg.DoModal()) { if (openFileDlg.m_ofn.Flags & OFN_ALLOWMULTISELECT) { // 多选模式 POSITION startPos = openFileDlg.GetStartPosition(); // 获取已选择的文件列表的起始位置 while (startPos != NULL) { selectFiles.push_back(openFileDlg.GetNextPathName(startPos)); } } else { // 单选模式 selectFiles.push_back(openFileDlg.GetPathName()); } } else { TRACE(_T("User cancel select!")); } for (auto& filePath : selectFiles) { TRACE(filePath); }
// 获取保存文件名 TCHAR szFilter[] = _T("Text Files(*.txt;*.csv)|*.txt; *.csv||"); CFileDialog saveFileDlg(FALSE/*FileSaveAs*/, _T("txt"), // 默认文件扩展名 NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT/*文件名已存在时,询问是否覆盖*/, szFilter, this); saveFileDlg.m_ofn.lpstrTitle = _T("文本文件保存");// 可以设置对话框的标题 if (IDOK == saveFileDlg.DoModal()) { CString filePath = saveFileDlg.GetPathName(); SetDlgItemText(IDC_EDIT, filePath); }
// 创建多级目录 CString dirPath = _T("D:\Te\a\"), tmpDir; int startPos = dirPath.Find(_T("\"), 0); while (startPos != -1) { tmpDir = dirPath.Left(startPos); BOOL isOk = CreateDirectory(tmpDir, NULL); startPos = dirPath.Find(_T("\"), startPos + 1); }
// 查找指定文件夹下的特定类型文件(不查找子文件夹) void FindFileInDir(const CString& findDir/*D:\Dir\*/, const CString& fileType/*csv*/, std::vector<CString>& vecFindFilePath) { CFileFind finder; CString tmpFindName; if (fileType.Find(_T(".")) != -1) { tmpFindName = findDir + _T("*") + fileType; } else { tmpFindName = findDir + _T("*.") + fileType; } BOOL isFind = finder.FindFile(tmpFindName); // start find CString findPath; while (isFind) { isFind = finder.FindNextFile(); // find a file if (finder.IsDirectory() || finder.IsDots()) { continue; } else { vecFindFilePath.push_back(finder.GetFilePath()); } } finder.Close(); }
//std::vector<CString> vecFind; //FindFileInDir(_T("D:\"), _T(".csv"), vecFind); //for (auto& elem : vecFind) { // CString strItem = _T(""); // strItem.Format(_T("%d"), m_list.GetItemCount()); // m_list.InsertItem(m_list.GetItemCount(), strItem); // m_list.SetItemText(m_list.GetItemCount() - 1, 1, elem); //}
// CString实现按字符分割功能
std::vector<CString> CMFCOperationTestDlg::CStringSplit(const CString& srcStr, const CString& seperator) { std::vector<CString> vecSubStrs; CString tmpStr = _T(""); int startPos = 0; int endPos = srcStr.Find(seperator, startPos); while (endPos != -1) { tmpStr = srcStr.Mid(startPos, endPos - startPos); tmpStr.Trim(); vecSubStrs.push_back(tmpStr); startPos = endPos + 1; endPos = srcStr.Find(seperator, startPos); } // the last substr tmpStr = srcStr.Mid(startPos, srcStr.GetLength() - startPos); tmpStr.Trim(); vecSubStrs.push_back(tmpStr); return vecSubStrs; } // 测试代码 void InitListControl() { //LONG lStyle; //lStyle = GetWindowLong(m_list.m_hWnd, GWL_STYLE); //获取当前窗口style //lStyle &= ~LVS_TYPEMASK; //清除显示方式位 //lStyle |= LVS_REPORT; //设置style //lStyle |= LVS_SINGLESEL; //单选模式 //SetWindowLong(m_list.m_hWnd, GWL_STYLE, lStyle); //设置style m_list.ModifyStyle(0, LVS_REPORT | LVS_SINGLESEL); DWORD dwStyle = m_list.GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; //选中某行使整行高亮(只适用与report风格的listctrl) dwStyle |= LVS_EX_GRIDLINES; //网格线(只适用与report风格的listctrl) dwStyle |= LVS_EX_CHECKBOXES; //item前生成checkbox控件 m_list.SetExtendedStyle(dwStyle); //设置扩展风格 m_list.InsertColumn(0, _T("序号"), LVCFMT_LEFT, 50); // 左对齐 50 m_list.InsertColumn(1, _T("路径"), LVCFMT_LEFT); m_list.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); // 最后一列自适应宽度 } std::vector<CString> vec = CStringSplit(_T("a, b,c, d, f, e, rryyyu, tyuyuiii, eeeee, eetw,wwerty"), _T(",")); for (int i = 0; i < vec.size(); ++i) { CString strItem = _T(""); strItem.Format(_T("%d"), i + 1); m_list.InsertItem(i, strItem); for (int j = 1; j < m_list.GetHeaderCtrl()->GetItemCount(); ++j) { m_list.SetItemText(i, j, vec.at(i)); } }
// 按行读取文本文件如txt,csv等 BOOL ReadTextFile(const CString& filePath,std::vector<CString>& outData) { #if 1 CStdioFile fileOutput; // 继承自CFile,默认是文本模式 CFileException ex; // Open if (!fileOutput.Open(_T("D:\mytest.csv"), CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate | CFile::shareDenyWrite, &ex)) { // Abort和Close的区别:abort不会抛出异常,即使文件没有打开或者已关闭 fileOutput.Abort(); // close file safely and quietly // ex.ReportError(); TCHAR szCause[255]; ex.GetErrorMessage(szCause, 255); // eg: 没有找到文件D:\mytest.csv CString strFormatted = _T("The data file could not be opened because of this error: "); strFormatted += szCause; TRACE(strFormatted); } // move to file end fileOutput.SeekToEnd(); // Write by line for (int i = 0; i < 100; ++i) { fileOutput.WriteString(_T("this,is,a,text,file,write,demo ")); } fileOutput.Close(); #endif CStdioFile fileIn; CFileException exp; // Open if (!fileIn.Open(filePath, CFile::modeRead, &exp)) { // Abort和Close的区别:abort不会抛出异常,即使文件没有打开或者已关闭 fileIn.Abort(); // close file safely and quietly exp.ReportError(); // if an error occurs, just make a message box return FALSE; } // Read CString strRead = _T(""); while (fileIn.ReadString(strRead)) { #if 1 // 内容读取到CListCtrl int cnt = m_list.GetItemCount(); // 当前列表的行数 int col = m_list.GetHeaderCtrl()->GetItemCount();// 列数 CString strItem = _T(""); strItem.Format(_T("%d"), cnt + 1); m_list.InsertItem(cnt, strItem);// 尾部插入行,及第1列内容 // 剩余的列(当前列表一共2列) for (int j = 1; j < col; ++j) { m_list.SetItemText(cnt, j, strRead); } #endif } fileIn.Close(); return TRUE; }
// CFile读写二进制文件 bool BinaryFile(LPCTSTR pszSource) { // constructing these file objects doesn't open them CFile sourceFile; // we'll use a CFileException object to get error information CFileException ex; // open the source file for reading if (!sourceFile.Open(pszSource, CFile::modeRead | CFile::shareDenyWrite, &ex)) { // complain if an error happened // no need to delete the ex object TCHAR szError[1024] = { 0 }; ex.GetErrorMessage(szError, 1024); _tprintf_s(_T("Couldn't open source file: %1024s"), szError); TRACE(szError); return false; } else { BYTE buffer[4096]; DWORD dwRead; do { dwRead = sourceFile.Read(buffer, 4096); } while (dwRead > 0); sourceFile.Close(); } return true; #if 0 CFile cfile; cfile.Open(_T("Write_File.dat"), CFile::modeCreate | CFile::modeReadWrite); char pbufWrite[100]; memset(pbufWrite, 'a', sizeof(pbufWrite)); cfile.Write(pbufWrite, 100); cfile.Flush(); cfile.SeekToBegin(); char pbufRead[100]; cfile.Read(pbufRead, sizeof(pbufRead)); ASSERT(0 == memcmp(pbufWrite, pbufRead, sizeof(pbufWrite))); //example for CFile::Remove TCHAR* pFileName = _T("Remove_File.dat"); try { CFile::Remove(pFileName); } catch (CFileException* pEx) { TRACE(_T("File %20s cannot be removed "), pFileName); pEx->Delete(); } // rename file TCHAR* pOldName = _T("Oldname_File.dat"); TCHAR* pNewName = _T("Renamed_File.dat"); try { CFile::Rename(pOldName, pNewName); } catch (CFileException* pEx) { TRACE(_T("File %20s not found, cause = %d "), pOldName, pEx->m_cause); pEx->Delete(); } #endif }
未完待续。。。