Important: Please read the Qt Code of Conduct -

Failed to open file when I use fstream

  • I'm new to Qt Creator so I'm not quite sure how the filing of it works... I created a simple fstream program that reads the text inside a .txt file and displays it in the terminal. The issue is that it doesn't seem to be able to find the .txt file...


    #include <iostream>
    #include <fstream>
    using namespace std;
    int main(){
        ifstream myFile;
        string name;"Test.txt");
            getline(myFile, name);
            cout << name << endl;
            cout << "Failed to open file!" << endl;
        return 0;

    TEMPLATE = app
    CONFIG += console c++11
    CONFIG -= app_bundle
    CONFIG -= qt
    SOURCES += \
    DISTFILES += \

    Please help a noob out.



  • Lifetime Qt Champion

    Hi and welcome to the forums
    will make it look in current folder which normally would be in the build folder where the .exe file is.
    Since the file is in the project folder, it wont find it.
    It does not know where the project folder is.

    Do you want the file to be embedded into the exe as a resource or be a free file you load at startup ?
    Since you are using ifstream, i assume free file as only QFile will load as ressource.

    You can place the text.file next to the exe and do>applicationDirPath() +"/Test.txt"); // note might be issue with / (qt) and \
    if you can , use QFile.

    The build folder you can see in the "projects" button to the left.

  • I want the .txt file to be a free file that I load up at startup.

    I have trouble using QFile. The project I created is just a plain C++ project.

    I copied the .txt file over to the build folder and now it works but that's a little frustrating... Why doesn't Qt Creator also copy the txt file over?

    I get errors when I use>applicationDirPath() +"/Test.txt");

    Thanks for your help I appreciate it, QT Creator is a little different from the IDEs I'm used too(>_<).

  • Lifetime Qt Champion

    @PsionicAlch said in Failed to open file when I use fstream:

    Why doesn't Qt Creator also copy the txt file over?

    Because you don't tell the build system to do so. QtCreator or anyone else don't do anything you did not tell them...

  • @Christian-Ehrlicher Ooooooo so how do you tell the build system to copy it over to the build folder? (0_0)

  • @PsionicAlch

    Hi! First of all if you want to tell something to the build system, example Qt Creator, you should add the appropriate command to the .pro file, so it will manage for you the pre/post build steps.

    Also, you can create the file using C++:

        QFile myFile(QApplication::applicationDirPath() + "/Test.txt");;
        if (myFile.isOpen()) {
            qDebug() << "File is open!";
        } else {
            qDebug() << "Failed to open the file!";

    It should create the file in your application directory on the runtime.

  • Lifetime Qt Champion

Log in to reply