tags:

views:

3593

answers:

2

I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at opendir() and telldir(), but telldir() returns a off_t (long int), so it really doesn't help me. How can I get the current path in a string (char array)?

+2  A: 

Look up the man page for getcwd.

CAdaker
+16  A: 

Had a look at getcwd?

   #include <unistd.h>
   char *getcwd(char *buf, size_t size);

Simple example:

   #include <unistd.h>
   #include <stdio.h>
   #include <errno.h>

   int main() {
       char cwd[1024];
       if (getcwd(cwd, sizeof(cwd)) != NULL)
           fprintf(stdout, "Current working dir: %s\n", cwd);
       else
           perror("getcwd() error");
       return 0;
   }
Mic
Picking the pickiest of nits, <errno.h> seems unnecessary, and the program reports success even on failure via its exit status. Otherwise, a nice example.
Jonathan Leffler
Oh, and is it more conventional to use printf(...) in place of fprintf(stdout, ...)?
Jonathan Leffler