2012-04-24 20:38:38|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, MFC, 操作系统, 文件操作|来源:唯设编程网
项目经常需要获取当前目录和指定应用程序的目录,这就需要用到两个API函数:GetCurrentDirectory和GetModuleFileName,本文将摘录MSDN对这两个函数的解释并给出实际的使用案例。
Retrieves the current directory for the current process.
DWORD WINAPI GetCurrentDirectory( __in DWORD nBufferLength, __out LPTSTR lpBuffer );
The length of the buffer for the current directory string, in TCHARs. The buffer length must include room for a terminating null character.
A pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory.
To determine the required buffer size, set this parameter to NULL and the nBufferLength parameter to 0.
If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
If the buffer that is pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, in characters, including the null-terminating character.
Each process has a single current directory that consists of two parts:
To set the current directory, use the SetCurrentDirectory function.
In certain rare cases, if the specified directory is on the current drive, the function might omit the drive letter and colon from the path. Therefore, the size that is returned by the function might be two characters less than the size of the specified string, not including the terminating null character. This behavior might occur in edge situations such as in a services application. If you need the drive letter, make a subsequent call to GetFullPathName to retrieve the drive letter.
使用实例:
bool ReadIni() { char databuf[1024]; char filepath[1024]; memset(databuf,0,1024); memset(filepath,0,1024); GetCurrentDirectory(1024,filepath); strcat(filepath ,"" ); strcat(filepath ,"database.ini" ); CFile file; if ( !file.Open(filepath,CFile::modeRead)) { return false; } file.Close(); memset(databuf,0,1024); GetPrivateProfileString("oracle","user id","",databuf,1024,filepath); m_sUserId = databuf; memset(databuf,0,1024); GetPrivateProfileString("oracle","password","",databuf,1024,filepath); m_sPassword = databuf; memset(databuf,0,1024); GetPrivateProfileString("oracle","data source","",databuf,1024,filepath); m_sDataSource = databuf; memset(databuf,0,1024); memset(filepath,0,1024); return true; }