Reputation: 55
I have to send a C++ project to my university professor.
This project uses QWidget, c++ classes and two .txt file that works as "database" where store my information.
When I open the project a QList is automatically filled up with the data stored in the .txt file.
The problem is that I have to put the .txt file in the build-directory if i want that the project use the data inside of it.
There is a way to put the .txt files into the directory where are stored all the .cpp and .h files?
The code that i used to open the file is:
std::ifstream in("file.txt");
but this open the file only if it is in the build-directory. I would like to change the path where the project look for the file.
Thanks
Upvotes: 1
Views: 10161
Reputation: 581
Suppose my cpp file "1505010.cpp" that I'm editing is here:
my .txt file is inside here test cases/1/scene.txt. Shown in the image below:
For this case, my cpp code should look like this:
void readFromFile()
{
string line;
sceneFile.open("./test cases/1/scene.txt");
if(sceneFile.is_open()){
while(getline(sceneFile, line)){
cout << line << endl;
}
sceneFile.close();
}
else {
cout << "Unable to open file";
}
}
Should be careful with "/" and "\". In this case we use "/" (forward slash).
Upvotes: 1
Reputation: 1
option 1: You need to use SetCurrentDirectory()
to set the current directory once you finished your operation revert it to the old one, before setting the current directory , you can get the current directory by using GetCurrentDirectory()
, preserve this in cache after your operation set it back again by using SetCurrentDirectory()
.
option 2: You need to pass entire path for the file (absolute path).
Upvotes: 0
Reputation: 4189
If relative path is provided as in your case (you also can provide absolute path like "/etc/file" or "C:\\Windows\\file") you can navigate to sub directory using "/"(or in windows "\\") and ".." to navigate to parent directory like "../Data/file". More about this you can find here. Working directory (starting directory) is by default where "exe" file is, but it can be changed from inside and outside the application. But there is one problem with what you want:
is a way to put the .txt files into the directory where are stored all the .cpp and .h files
This directory is normally not included with application as it contains only source code and probably you don't want to shipped it with application.
Upvotes: 1
Reputation: 4193
If you do not consider manual path specification as it mentioned in duplicated questions, I recommend using either QStandardPaths
like this
auto dbFilePath = QStandardPaths::locate(QStandardPaths::AppDataLocation, "file.txt", QStandardPaths::LocateFile);
or/and QCoreApplication::applicationDirPath
.
Use one of them or write some logic based on those two to locate your files independently of your current working directory. Mind that in those cases you need preinstall files, and then you can ship it with the files as resources.
Upvotes: 1