Question

I am writing a c program in linux. Commands like execv() require a path in the form of a c string. Is there a command that will return the current path in the form of a c style string?

Was it helpful?

Solution

getcwd():

SYNOPSIS

#include <unistd.h>

char *getcwd(char *buf, size_t size);

DESCRIPTION

The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified.

RETURN VALUE

Upon successful completion, getcwd() shall return the buf argument. Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined....

OTHER TIPS

The path argument to execv() is the path to the application you wish to execute, not the current working directory (which will be returned by getcwd()) or the shell search path (which will be returned by getenv("PATH")).

Depending on what you're doing, you may get more mileage out of the system() function in the C library rather than the lower-level exec() family.

This is not ANSI C:

#include <unistd.h>

char path[MAXPATHLEN];
getcwd(path, MAXPATHLEN);
printf("pwd -> %s\n", path);

If the path can be a relative path, you should be able to use '.' or './' as the path. I'm not sure if it will work, but you could try it.

I am not a professional programmer so this isn't an exact answer.

What you need to do is grab the environment variable PWD (present working directory)

I'm not sure what the library it is in but it is a standard linux header.

I'll look around and see if I can find it.

edit:

I was thinking of ,getenv() which would help if you also need to run system commands and need the various bin paths located in PATH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top