Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix command result to a variable - char*

Tags:

c

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 just "pwd".

Thanks.

like image 577
hari Avatar asked Apr 17 '26 05:04

hari


2 Answers

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.

like image 73
Jerry Coffin Avatar answered Apr 18 '26 17:04

Jerry Coffin


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.

like image 30
Sherm Pendley Avatar answered Apr 18 '26 18:04

Sherm Pendley