0

I am trying to change the current working directory to the path of the executable, using chdir() in the following manner:

#include <iostream>
#include <string>
using namespace std;

int main(int argc,char *argv[]) {

    if(chdir(argv[0]) == 0) printf("In %s\n", argv[0]);
        else printf("Failed to change directory\n");
}

The output is:

Failed to change directory

Why doesn't chdir work with argv[0]? Other solutions for this issue would also be accepted.

Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
  • What command line arguments did you provide? – Mark Garcia Dec 14 '12 at 02:57
  • 2
    You're changing the directory to your executable file? Whatever for? In this situation the next thing I'd do is print `argv[0]` before anything else. Of course, debugging it and examining the values contained in `argv` works as well. – chris Dec 14 '12 at 02:58
  • I want my executable to be able to create new files from it's own path, rather than the shell's path – Yoav Kadosh Dec 14 '12 at 02:59
  • argv[1] fails as well @RetiredNinja – Yoav Kadosh Dec 14 '12 at 03:01
  • 1
    helpful link? http://stackoverflow.com/questions/13797599/get-the-app-path-without-the-app-name-at-the-end-of-the-app/13797801#13797801 – billz Dec 14 '12 at 03:02

2 Answers2

4

You need to use splitpath or similar to remove the executable's name from argv[0]. You can't chdir to a file.

[edit] Sorry, I think splitpath is a Windows thing... Just do this:

char *dirsep = strrchr( argv[0], '/' );
if( dirsep != NULL ) *dirsep = 0;

Now argv[0] has been trimmed to remove the executable name.

Beware that the command-line might not contain any directory at all.


You are sort of breaking the entire Linux (I assume) paradigm by trying this... You shouldn't have to know where your executable is stored. Generally you specify output in one of the following ways:

  1. In a configuration file (which for example might be kept in /usr/local/etc, or the user's home directory, or given on the command line);

  2. Using command line options;

  3. Writing to standard output.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • Is there any built-in function to do that? – Yoav Kadosh Dec 14 '12 at 03:02
  • 1
    Actually, `splitpath` is a Windows thing I think. Sorry. Look, you could just do `strrchr( argv[0], '/' )`. If it's non-null, set the character at the returned pointer to 0. Now `argv[0]` contains a path. – paddy Dec 14 '12 at 03:09
1

Because argv[0] has the path to the current script, including the current script. So you need to trim everything following the last path separator ("/", ":", or "\" depending on your platform) and pass the result of that to chdir.

hd1
  • 33,938
  • 5
  • 80
  • 91