简体   繁体   中英

Can' open File in C++ under MacOs

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:

  1. See where the application binary is.
  2. Copy db.config there if it isn't there already.
  3. In your code, change to that directory before you load the file, which you can do with Qt like this: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM