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)?
+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
2008-11-18 11:38:24
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
2008-11-18 14:18:07
Oh, and is it more conventional to use printf(...) in place of fprintf(stdout, ...)?
Jonathan Leffler
2008-11-18 14:18:53