开发者

unix command result to a variable - char*

开发者 https://www.devze.com 2023-02-19 23:14 出处:网络
How can I assign \"pwd\" (or any other command in that case) result (present working dir) to a variable which is char*?

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 ju开发者_如何学运维st "pwd".

Thanks.


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.


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.


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


#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.


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);

0

精彩评论

暂无评论...
验证码 换一张
取 消