简体   繁体   English

stat()在C ++中找不到文件

[英]stat() doesn't find a file in c++

on Linux 12.04 I have an executable file located in say: 在Linux 12.04上,我有一个可执行文件,位于:

/a/b/exe

and a config file on 和一个配置文件

/a/b/config

when doing: 做的时候:

cd /a/b/
./exe

everything's ok and the stat function finds the file config on /a/b/ 一切正常,并且stat函数在/ a / b /上找到文件配置

HOWEVER,when running from root 但是,从根目录运行时

/a/b/exe

the stat doesn't find the config file 统计信息找不到配置文件

any idea why? 知道为什么吗?

it makes it impossible to run the binary using a script that isn't ran from the folder of the exe. 这样就不可能使用不是从exe文件夹运行的脚本来运行二进制文件。

Edit 编辑

The call looks like this: 呼叫看起来像这样:

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;
}

In first case cd ..., run exe you change current working directory before executing the program, in second case you launch exe without changing current working directory, and I think in your program you use a relative path to open your config(for example ./config or just config ) and it can't find it from current working directory. 在第一种情况下cd ..., run exe您在执行程序之前先更改当前工作目录,在第二种情况下启动exe而不更改当前工作目录,我想在您的程序中使用相对路径来打开配置文件(例如./config或仅config ),则无法从当前工作目录中找到它。 easiest workaround is to change working directory at start of your app: 最简单的解决方法是在应用启动时更改工作目录:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM