I think I understand most of what I am reading, but what I don't understand is how to tell a program where to save a file. Let's say I want it to be saved in my ”Desktop” directory, normally I would point to:
~/Desktop
I have done a search on Google, but not found anything that clarifies this.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
string name;
int year;
ofstream testfile("~/Desktop/testfile.txt");
cout << "Write your name: ";
getline(cin, name);
cout << "How old are you? ";
cin >> year;
testfile.open ("testfile.txt"); // I have tried specifying the full
// pathname here as well - no dice!
testfile << "Your name is: "
<< name << ".\n"
<< "You are "
<< year << " years.\n";
testfile.close();
return 0;
}
It works if I do not try to specify the full pathname, as such:
ofstream testfile;
Then the file is saved in the current directory, and the output is as expected. I'm sure I'm doing a really stupid mistake, nevertheless - I would appreciate if someone could point it out for me.
Thanks, I appreciate it, but I don't get it. Any chance you could point out in the code above what is wrong, and how it should be in order for it to work?
Maybe "~" doesn't expand to your actual home so the file won't open.
You gen get the actual home directory from the environment ( getenv("HOME") ) and then append the relative path
eg: ( string(getenv("HOME"))+"/Desktop/testfile.txt" ).c_str() http://www.cplusplus.com/reference/clibrary/cstdlib/getenv/