I just started reading and writing to text documents to save data from some of my programs. I'm just using an example as a test program as shown below. The thing I'm wondering is where does it put the text document so I can read it later? Also, how can I control where the document goes and what folder i can find a document in? The examples I've seen don't show how to specify where it goes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Using a generic program for a start.
#include <Windows.h>
#include <iostream>
usingnamespace std;
#include <fstream>
usingnamespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
Sleep(5000);
return 0;
}
If you're running your app from Visual Studio, the file will turn up in the same folder as the vcproj file (the project folder is set as the working directory by default.)
But you can set the Working Directory property on the Debugging page of the projects properties if you want it written elsewhere. I usually edit my working directory to be the output directory ($(SolutionDir)$(ConfigurationName) by default), which means the file is in the same folder as the exe.
You can specify a full or relative path when you open the file.
1 2
// write file to C:\temp
ofstream myfile ("c:\\temp\\example.txt");
1 2
// write to parent folder
ofstream myfile ("..\\example.txt");
I think I get it. I was using only one " \" instead of two, making it stuff like a new line. The thing with the relative location is also very helpful.