hey, had a question that I couldn't figure out. I'm writing a program for linux and I need to save things to a person's Desktop. Because of that, I need to know their username. I am aware of the linux commands whoami, id, etc, but they only print the current user's name, not return it so I can use it in the program. Is there any way to put in a variable what is put on the screen (and hopefully prevent it from being printed to the screen in the first place).

#include<iostream>
using namespace std;

int main()
{
	std::string name;
	name = system("whoami");
	cout << "Name is : " << name;
	cout << endl;
	return 0;
}

output:
user@user-desktop:~$ /home/user/Desktop/test
user
Name is :
user@user-desktop:~$

Thanks!
~J

you could use pipes. see man pages for popen()

is this correct usage?

#include<iostream>
using namespace std;

int main()
{
	FILE *name;
	name = popen("whoami", "r");
	cout << "Name is : " << name;
	pclose(name);
	cout << endl;
	return 0;
}

that still yields this:

user@user-desktop:~$ /home/user/Desktop/test
user
Name is :
user@user-desktop:~$

>>is this correct usage?
No. Just like any other C program you have to read the data from the file.

#include<iostream>
#include <cstdio>
using namespace std;

int main()
{
    char text[255];
    FILE *name;
    name = popen("whoami", "r");
    fgets(text, sizeof(text), name);
    cout << "Name is : " << text;
    pclose(name);
    cout << endl;
    return 0;
}

thank you, your a genius.

I would be able to do things so much easier if I knew certain functions existed.

>>I would be able to do things so much easier if I knew certain functions existed.
You will, eventually. It takes awhile to get all that suff straight in your head -- I know it did for me.

You can use environment variables to achieve this task. Use the function getenv(var) in <stdlib.h> to get the value of environment variable var. The variable "USER" or "USERNAME" hold the name of the current user. You can also use the variable "HOME" to directly get the path to the user's home directory. Here is an example code:

#include <iostream>
#include <stdlib.h>

using namespace std;

int main() {
	cout << getenv("USER") << endl;
	cout << getenv("HOME") << endl;
	return 0;
}

The output would be something like this:
user@user-desktop:~$ ./test
user
/home/user
user@user-desktop:~$

and I need to save things to a person's Desktop

the users home isnt nececerially thier desktop, the path for that depends on thier window manager / gui configuration.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.