Thread: Dir where application resides

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    41

    Dir where application resides

    Hello All,

    Im trying to get the working directory where my application resides. My actual code uses getcwd.

    Code:
    #include <unistd.h>
    #include <limits.h>
    
    main()
    {
    char *cwd;
    char buf[PATH_MAX+1];
              if((cwd = getcwd(buf, PATH_MAX+1)) == NULL) {
                          perror("pwd");
                              exit(1);
              }
    puts(cwd);
    }
    The result is the current working directory that my user is in the shell session.
    If I do this:

    cd /tmp
    /home/user/cwd

    the return is /tmp and not /home/user

    Is there a way to get the working directory where the app resides and not the cwd where the user is ?

    Thanks,

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You might be able to pull it from argv[0], but I don't think it's guaranteed to be accurate. If you're lucky it will store exactly what you typed to run the program. You'll just have to parse it into path and executable parts.
    If you understand what you're doing, you're not learning anything.

  3. #3

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    41
    Ok anonytmouse, understood ! I'll try argv[0] for now and think in a better solution for the next versions !

    Thanks for the help !

  5. #5
    Hamster without a wheel iain's Avatar
    Join Date
    Aug 2001
    Posts
    1,385
    Monday - what a way to spend a seventh of your life

  6. #6
    Registered User
    Join Date
    Dec 2004
    Posts
    41
    Hi iain,

    I've tryed getwd but it has the same result as getcwd. My code:

    Code:
    #include <unistd.h>
    #include <limits.h>
    
    main()
    {
      char buf[500];
      getwd(buf);
      printf("getwd: [%s]\n",buf);
    }
    The output was:
    $ cd /home/user/tmp
    $ ./getwd
    getwd: [/home/user/tmp]
    $ cd /tmp/
    $ /home/user/tmp/getwd
    getwd: [/tmp]
    $

    Thanks !

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with com application
    By amardon in forum C++ Programming
    Replies: 3
    Last Post: 10-06-2005, 05:50 AM
  2. MFC run application by clicking on file...
    By dug in forum Windows Programming
    Replies: 4
    Last Post: 12-02-2004, 04:33 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM