open file from root directory

How do you open a file from the root directory without have to type the complete path?

1
2
3
4
5
6
7
8
9
string path = "~/data/";
string file = path + "file.dat";

fstream f;
f.open(file.c_str(), ios::in);
if ( !f )
{
 cout << "I can't open " << file << "\n";
}


It prints it can't open the file.

But if I write

 
string path = "/home/nik/data/"; // my user directory 


it works well. Why???
I am not very sure, but I don't think that you should use
~

Try it with
string path = "/data/";
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <cerrno>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
//...
passwd* pwd=getpwuid(getuid());
if (!pwd)
	//Some error occurred.
//pwd->pw_dir now holds the user's ~ ("/home/nik", in this case).
//You should copy the string if you need to modify it. 
It works well. Thanks. :-)
Topic archived. No new replies allowed.