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

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 07:14   30   0

得到当前目录的函数:    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文件是在同个目录下)

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP