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

3
  • 2
    If everything you want is read the username you can use getenv man7.org/linux/man-pages/man3/getenv.3.html Commented Mar 15, 2015 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. Commented Mar 15, 2015 at 11:22
  • There's mostly C in the accepted answer there, except the std::string which you can easily replace with char *. Commented Mar 15, 2015 at 11:24

2 Answers 2

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?

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

1 Comment

haha wow ok, solved all my problems, thanks a lot!
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.

1 Comment

thanks @user1973385, the popen function is a useful lead, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.