Search code examples
c++fileioofstream

How to change file path of a variable file name?


I have found a very helpful question and answers here: How to create ofstream file with name of variable?

But because I have < 50 reputation on here, I cannot comment on the answer there.

I have the following code:

string fileName;
cout << "Enter file name: ";
cin >> fileName;
fileName += ".txt"; 
ofstream createFile;
createFile.open(fileName.c_str());

All I want to do is save the newly created variable name 'fileName.c_str()' to a certain path e.g /home/Data/.../fileName.c_str().

Every time I try to put the path in explicitly:

createFile.open("/home/Geant4/Data/.../fileName.c_str()"); 

it saves it as 'fileName.c_str()' in that particular path, without the new name. I can find no information online on changing paths of variable file names, so any help is appreciated.

Thank you.


Solution

  • try: createFile.open("/home/Geant4/Data/.../"+ filename);