I want to open and read a file in C++. Therefor I wrote the following code:
#include <fstream>
#include <iostream>
#include <string>
...
string line;
ifstream file;
file.open("./db.config");
if (file.is_open()) {
cout << "File is open" << endl;
getline(file, line);
file.close();
}else cout << "File is not open" << endl;
This code is written in the main.cpp. I verified that main.cpp and db.config are in the same directory.
I don't get any Compiletime oder Runtime Errors. It only prints "File is not open". I also tried it without "./" ( file.open("db.config"); ), but this also didn't work.
The problem is, the current working directory is not the one where db.config
file is located. You seem to have it in the same directory as the .cpp file. The current working directory is probably something different. Ultimately you need to decide where you want db.config
file to reside, there are many options, but here's simple solution:
db.config
there if it isn't there already.QDir::setCurrent(QCoreApplication::applicationDirPath());
Note that if the user runs the program from command line, and are allowed to give files as arguments, then changing working directory inside the program might make those files not be found. In that case, construct absolute path to db.config
instead of changing the working directory.
You could read QStandardPaths docs to get better idea on where you actually want to store the db.config
file. This depends on how you plan to distribute the application. If you just want to have it in .zip
or something, then same directory with application binary is probably fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.