I am developing a portable C++ application. Development environment is Linux. I have a code that loads data from Xml file and create a object model out of it. Currently path to file is provided as /home/myuser/projectdir/xmlfilename.xml. This is problematic when I use from a different computer where the home directory name will be different. I tried something like ~/myuserprojectdir/xmlfilename.xml but it didn’t worked.
So is there a standard method in defining file names that will work on variety of platforms without any issues? Or any standard method that will work on Linux machines?
Any thoughts?
You need to locate the user’s home directory. To do this, Use
getpwentto get the user record and from there the home directory. Then add the rest of the path to your xml file/myuserprojectdir/xmlfilename.xmlto the value you get.This will work even if the users’s home directory is not
/home/$USER. It works on linux and OSX, and will probably work on windows with cygwin installed.Here’s a working example with error checking omitted for clarity:
output:
This is how it works (from
man getpwent):To get the username, use
getlogin… here’s a snippet fromman getlogin.