0

I was wondering if anyone can help me:

I need to turn the output of the system command : whoami into a variable.

Example:

char *a;
a = system("whoami");
printf("username = %s",a);

I have tried a few methods such as printing the commands output to a text file like: whoami >> output.txt and than making the program read from that file, however i am encountering errors through that method. I also consider that method to be a little messy and unnecessary as im positive that there must be a way within C to let me do this.

This question may be a duplicate so please label as necessary(but also answer if capable)

Thanks a lot :)

user4493605
  • 391
  • 2
  • 18
  • 2
    If everything you want is read the username you can use getenv http://man7.org/linux/man-pages/man3/getenv.3.html – dfranca Mar 15 '15 at 11:18
  • Thank you @volerag however im not sure that will help unless C and C ++ are more similar than i think they are, thank you anyway though. – user4493605 Mar 15 '15 at 11:22
  • There's mostly C in the accepted answer there, except the `std::string` which you can easily replace with `char *`. – shauryachats Mar 15 '15 at 11:24

2 Answers2

1

If everything you want is to read an environment variable in a POSIX environment, you can simply call getenv: http://man7.org/linux/man-pages/man3/getenv.3.html

#include <stdlib.h>
#include <stdio.h>

int main() {
        char* username = getenv("USER");
        printf("username = %s\n", username);
        return 0;
}

If you want something more complex, you can use popen: http://man7.org/linux/man-pages/man3/popen.3.html to create a pipe to a process and read from stdout, this answer should help in that case: C: Run a System Command and Get Output?

Community
  • 1
  • 1
dfranca
  • 5,156
  • 2
  • 32
  • 60
0

This should do the trick. I haven't tested it myself, but I checked and its listed in the Linux man pages so I'm sure its kosher.

Community
  • 1
  • 1
user1973385
  • 145
  • 1
  • 1
  • 8