c++:讀取配置檔案
namespace fs = boost::filesystem;
fs::path objPath = strFilePath; // strFilePath--目錄
objPath/=strFileName;// strFileName--檔名
if(objPath.is_absplute())
{
strFullPath = objPath.string();
return;
}
/* 如果是相對路徑,轉換為絕對路徑*/
string strCurDir=CFileUtil::getCurModuleDir();
if(strCurDir.empty())
{
return ;
}
fs::path objFullPath = strCurDir;
objFullPath/=objPath;
strFullPath=objFullPath.string();
return ;
//
std::string CFileUtil::getCurModuleDir()
{
std::string strCurrModuleDirectory;
enum { BUF_LEN = 1024 };
char pcDirectory[BUF_LEN];
::memset(pcDirectory, 0, sizeof(pcDirectory));
#if defined(WIN32)
::GetModuleFileNameA(NULL, pcDirectory, BUF_LEN);
#elif defined(__linux)
readlink("/proc/self/exe", pcDirectory, BUF_LEN);
#elif defined(_AIX)
char relativePath[BUF_LEN];
char psinfo_path[BUF_LEN];
psinfo_t psinfo;
sprintf_s(psinfo_path, BUF_LEN, "/proc/%d/psinfo", getpid());
int fd;
ssize_t bytes_read;
fd = open(psinfo_path, O_RDONLY);
if (fd != -1)
{
bytes_read = read(fd, (void *)(&psinfo), sizeof(psinfo_t));
if (bytes_read > 0)
{
char shell_command[BUF_LEN];
sprintf(shell_command, "which %s 2>/dev/null", psinfo.pr_fname);
//呼叫 shell命令從環境變數中查詢當前程式所在的絕對路徑。
FILE *fp = popen(shell_command, "r");
if (fp != NULL)
{
fgets(pcDirectory, sizeof(pcDirectory), fp);
pclose(fp);
}
if (pcDirectory[0] != '/') //如果沒有找到
{
char*** pArgv = (char***)psinfo.pr_argv;
if (pArgv[0][0][0] == '/')
{
strcpy(relativePath, pArgv[0][0]);
}
else
{
getcwd(relativePath, BUF_LEN);
strcat(relativePath, "/");
strcat(relativePath, pArgv[0][0]);
}
realpath((const char*)relativePath, (char*)pcDirectory);
}
}
else
{
close(fd);
return "";
}
close(fd);
}
else
{
return "";
}
#elif defined(__sun)
char pCurrentPath[BUF_LEN];
char pExecPath[BUF_LEN];
const char *p = getexecname();
getcwd(pCurrentPath, BUF_LEN);
strcpy(pExecPath, p);
if (pExecPath[0] == '/')
{
strcpy(pcDirectory, pExecPath);
}
else
{
strcat(pCurrentPath, "/");
strcat(pCurrentPath, pExecPath);
strcpy(pcDirectory, pCurrentPath);
}
#endif
for (int i = (int)strlen(pcDirectory); i >= 0; i--)
{
#if defined(WIN32)
if (pcDirectory[i] == '\\')
#else
if (pcDirectory[i] == '/')
#endif
{
pcDirectory[i + 1] = '\0';
break;
}
}
return pcDirectory;
}