-1

在 Linux 12.04 上,我有一个可执行文件位于:

/a/b/exe

和一个配置文件

/a/b/config

做的时候:

cd /a/b/
./exe

一切正常,stat 函数在 /a/b/ 上找到文件配置

但是,从 root 运行时

/a/b/exe

stat 找不到配置文件

知道为什么吗?

它使得无法使用不是从 exe 文件夹中运行的脚本来运行二进制文件。

编辑

调用如下所示:

struct stat stFileInfo;
bool blnReturn;
int intStat;

// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
if(intStat == 0) {
// We were able to get the file attributes
// so the file obviously exists.
    blnReturn = true;
} else {
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
    blnReturn = false;
}
4

1 回答 1

2

在第一种情况下cd ..., run exe,您在执行程序之前更改当前工作目录,在第二种情况下,您在不更改当前工作目录的情况下启动 exe,我认为在您的程序中您使用相对路径来打开您的配置(例如./config或只是config),它可以' t 从当前工作目录中找到它。最简单的解决方法是在应用程序启动时更改工作目录:

int main(int argc, char** argv) {
    std::string s( argv[0] );  // path to the program
    std::string::size_type n = s.rfind( '/' );
    if( n != std::string::npos ) {
        std::system( ("cd " + s.substr(0, n)).c_str() );
    }

    // rest of your code
}
于 2012-10-22T16:58:34.787 回答