-1

on Linux 12.04 I have an executable file located in say:

/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/

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.

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;
}
Community
  • 1
  • 1
Alon_T
  • 1,430
  • 4
  • 26
  • 47

1 Answers1

2

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. 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
}
BigBoss
  • 6,904
  • 2
  • 23
  • 38