Create files in the Home folder with C ++

0

In c ++, creating files is very simple, just include the fstream library and use

ofstream arquivo;

file.open ("variables.txt");

However this generates the file in the project folder and I would like to generate the file in some other folder, such as Desktop for example. But there is a small problem in these cases, on each computer with linux the path to the desktop is different. In my for example I could simply do this:

iofstream arquivo;
arquivo.open("/home/silas/desktop/arquivo.txt");

But on another computer it might be:

iofstream arquivo;
arquivo.open("/home/lucas/desktop/arquivo.txt");

One possible solution could be to use

system("whoami");

It writes in the terminal the name of the user, however I do not know any way to put the result of the command to a string. So, is there any way to do this? Or at least some function that returns the user of the system, that would help a lot.

    
asked by anonymous 19.04.2018 / 01:53

2 answers

2

It depends on what you need to do. The environment variable HOME can be manipulated by the user allowing a false place to be specified. To get the true home you can use the getpwuid function. To get the home that the user wants to inform you, use getenv .

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <iostream>

using namespace std;

int main( void )
{
  uid_t uid = getuid();
  cout << "UID: " << uid << endl;
  cout << "HOME(real): " << getpwuid( uid )->pw_dir << endl;
  cout << "HOME(root): " << getpwuid( 0 )->pw_dir << endl;
  cout << "HOME(env): " << getenv( "HOME" ) << endl;
  return 0;
}

The output of the above program to a forced home can be:

$ HOME="/tmp/xyz" ./a.out 

UID: 1001
HOME(real): /home/intmain/geraldoim
HOME(root): /root
HOME(env): /tmp/xyz
    
19.04.2018 / 07:57
3

You can uasr the getenv () function to get the $ HOME value:

const char* s = getenv("HOME");
    
19.04.2018 / 02:05