2

How can I assign "pwd" (or any other command in that case) result (present working dir) to a variable which is char*?

command can be anything. Not bounded to just "pwd".

Thanks.

3

5 Answers 5

6

Start with popen. That will let you run a command with its standard output directed to a FILE * that your parent can read. From there it's just a matter of reading its output like you would any normal file (e.g., with fgets, getchar, etc.)

Generally, however, you'd prefer to avoid running an external program for that -- you should have getcwd available, which will give the same result much more directly.

Sign up to request clarification or add additional context in comments.

Comments

5

Why not just call getcwd()? It's not part of C's standard library, but it is POSIX, and it's very widely supported.

Anyway, if pwd was just an example, have a look at popen(). That will run an external command and give you a FILE* with which to read its output.

1 Comment

Thanks but "pwd" is just an example, I am looking for a generalize solution for any command.
2

There is a POSIX function, getcwd() for this - I'd use that.

1 Comment

Thanks but "pwd" is just an example, I am looking for a generalize solution for any command.
2
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
    char *dir;
    dir = getcwd(NULL, 0);
    printf("Current directory is: %s\n", dir);
    free(dir);
    return 0;
}

I'm lazy, and like the NULL, 0 parameters, which is a GNU extension to allocate as large a buffer as necessary to hold the full pathname. (It can probably still fail, if you're buried a few hundred thousand characters deep.)

Because it is allocated for you, you need to free(3) it when you're done. I'm done with it quickly, so I free(3) it quickly, but that might not be how you need to use it.

Comments

0

You can fork and use one of the execv* functions to call pwd from your C program, but getting the result of that would be messy at best.

The proper way to get the current working directory in a C program is to call char* getcwd(char* name, size_t size);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.