您的位置:首页 > 其它

VC得到当前目录与得到应用程序目录的一个应用

2010-11-17 22:55 387 查看
得到当前目录的函数:    GetCurrentDirectory
  得到应用程序目录的函数是: GetModuleFileName
  用法都很简单,不知道就看MSDN吧。

  我先用这2个函数分别写一个实现同一个功能的函数。

以下是代码片段:
  // 函 数 名:ReadIni
// 功能描述:读配置文件database.ini(用来配置oracle数据库的用户名、密码和服务名的),成功返回true,否则返回false
// 输入参数:void
// 输出参数:bool
// 创建日期:2006-5-25
// 修改日期:2006-5-25
// 作 者:joinclear
// 附加说明:无
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;
}

bool ReadIni()
{

char databuf[1024];

CString sPath;
GetModuleFileName(NULL,sPath.GetBufferSetLength(1023),1024);
sPath.ReleaseBuffer();
int nPos;
nPos = sPath.ReverseFind(’//’);
sPath = sPath.Left(nPos);

   CString str = sPath + "//database.ini";

char filepath[1024];
strcpy(filepath,(LPSTR)(LPCTSTR)str);

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;
}
你用这2个函数分别执行一下,发现并没有任何的不一样。

但是当你在同一个程序里面,哪怕是不同的界面,如果你打开一个文件选择或保存对话框的时候,用GetCurrentDirectory函数的这种方法就不行了。因为当前目录被你的文件选择或保存对话框修改了。

这时用GetModuleFileName函数的方法就很有必要了,但要注意的是GetModuleFileName得到的应用路径是包括EXE名的,所以EXE名还是要去掉的。(前提是database.ini和EXE文件是在同个目录下)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐