Create files in the Home folder with C++

Asked

Viewed 254 times

0

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

ofstream arquivo;

open file("variables.txt");

But 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. Only that there is a small problem in these cases, in each computer with linux the path to the desktop is different. In mine for example I could just do that:

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

But on another computer maybe:

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

A possible solution could be to use the

system("whoami");

That writes the name of the user to the terminal, but I don’t 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 system user, this would help a lot.

  • Why don’t you use ~/desktop/arquivo.txt ?

2 answers

3

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

const char* s = getenv("HOME");
  • 1

    Just remember it’s from cstdlib that function

  • Thanks for the comment, I even thought it was something POSIX-only

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 real home you can use the function getpwuid. To get the home the user wants to inform you use the 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, for a forced home may be:

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

UID: 1001
HOME(real): /home/intmain/geraldoim
HOME(root): /root
HOME(env): /tmp/xyz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.