Skip to content

Instantly share code, notes, and snippets.

@calebreister
Created March 6, 2014 05:49
Show Gist options
  • Save calebreister/9383299 to your computer and use it in GitHub Desktop.
Save calebreister/9383299 to your computer and use it in GitHub Desktop.
Simple code to get the user's home directory. With that information, it is much easier to get to a location on the hard drive such as documents or customization storage.
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int myuid;
passwd *homedir;
myuid = getuid();
homedir = getpwuid(myuid);
string path = homedir->pw_dir;
path += "/file.txt";
cout << "File written to: " << path.c_str() << endl;
ofstream myFile;
myFile.open(path.c_str());
myFile << "THIS IS SOME OUTPUT." << endl
<< "Hopefully there was nothing in this file, because it was just overwritten." << endl;
myFile.close();
}
//NOTE: Unix uses "/" to delimit a directory level, you may need to change
//that in order for your program to work correctly in Windows.
//When putting in a file path for opening a file, you will need to use the c_str() method
//This is because the open method only accepts cstrings. The string type in C++ is a class.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment