gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:14 24 4
gpt4 key购买 nike

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

/a/b/exe

和一个配置文件

/a/b/config

做的时候:

cd /a/b/
./exe

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

但是,当从 root 运行时

/a/b/exe

统计信息未找到配置文件

知道为什么吗?

它使得无法使用不是从 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;
}

最佳答案

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

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
}

关于c++ - stat() 在 C++ 中找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13016035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com