MFC 檢測文件存在、獲取當前路徑、新建文件夾


直接上代碼:

///////查看執行文件的路徑下面是否有db文件夾,若沒有則新建/////////

CFileFind cff;
if (cff.FindFile(_T("db")) == 0)     //當前路徑,沒找到db文件夾
{
  CString strText;
  TCHAR exepath[MAX_PATH]={0};
  ::GetModuleFileName(NULL,exepath,MAX_PATH);   //獲取exe路徑,存於exepath中
  strText=exepath;                  
  strText = strText.Left(strText.ReverseFind('\\'));   //找到路徑中倒數第一個/,並將其后面的字符掐掉,注意轉義字符的表達\\
  strText += _T("\\");
  strText += _T("db");      //新的路徑,新的文件名
CreateDirectory(strText,NULL); // 生成db文件夾
}

 

以下為轉載,未核實

1. 獲取Debug或Release所在的路徑
CString GetModuleDir() 

 HMODULE module = GetModuleHandle(0); 
 char pFileName[MAX_PATH]; 
 GetModuleFileName(module, pFileName, MAX_PATH); 
 
 CString csFullPath(pFileName); 
 int nPos = csFullPath.ReverseFind( _T('\\') ); 
 if( nPos < 0 ) 
  return CString(""); 
 else 
  return csFullPath.Left( nPos ); 
}

2. 獲取當前工作路徑(dsp所在路徑)

//獲取工作路徑
CString GetWorkDir() 
{  
 char pFileName[MAX_PATH]; 
 int nPos = GetCurrentDirectory( MAX_PATH, pFileName); 
 
 CString csFullPath(pFileName);  
 if( nPos < 0 ) 
  return CString(""); 
 else 
  return csFullPath; 
}

以下為轉載,未核實

C/MFC如何獲得應用程序當前路徑(整理)

第一種方法:
DWORD GetCurrentDirectory(
  DWORD nBufferLength,  // size, in characters, of directory buffer
  LPTSTR lpBuffer       // pointer to buffer for current directory
);
BOOL SetCurrentDirectory(
  LPCTSTR lpPathName   // pointer to name of new current directory
);
第二種方法
用GetModuleFileName得到應用程序的文件名(第一個參數為NULL)
再用_splitpath分析文件名得到路徑
例如:
//得到當前路徑
 /*char buf[100];
 GetCurrentDirectory(sizeof(buf),buf);
 MessageBox(buf);
 HINSTANCE hInst=NULL;
 hInst=AfxGetApp()->m_hInstance;
 char path_buffer[_MAX_PATH];
 GetModuleFileName(hInst,path_buffer,sizeof(path_buffer));//得到exe文件的全路徑
 //分離路徑和文件名。
    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
 _splitpath( path_buffer, drive, dir, fname, ext );
 CString Path;
 Path.Format("%s%s",drive,dir);
char path[300];
strcpy(path,drive);
strcat(path,dir);
又或:
TCHAR exeFullPath[MAX_PATH];
    CString strPath;
    GetModuleFileName(NULL,exeFullPath,MAX_PATH);
    strPath=(CString)exeFullPath;
     int position=strPath.ReverseFind('\\');
    strPath=strPath.Left(position+1); 

    TCHAR FilePath[MAX_PATH];
    GetModuleFileName(NULL,FilePath,MAX_PATH);
    (_tcsrchr(FilePath,'\\'))[1] = 0; 
    lstrcat(FilePath,_T("MY.ini")); 

第三種方法:
VC中__argv[0]可以得到exe的程序名,然后用_splitpath可以分解得到程序路徑。
第四種方法
#include<direct.h>
char buf[_MAX_PATH];
_getcwd(buf,_MAX_PATH);
第四種是得到操作系統所在的目錄
char buf[100];
 GetSystemDirectory(buf,100);
 MessageBox(buf);
 
以下未核實
http://www.cnblogs.com/project/archive/2010/12/02/1894494.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM