Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Program cannot access file.



  • Hi guys. I am quite new to qtcreator and I tried to make a simple program that opened up a file, read the contents and set a label equal to it. My code is as follows:

    main.cpp

    #include "mainwindow.h"
    
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
        return a.exec();
    }
    
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <iostream>
    #include <chrono>
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <QDebug>
    
    std::string readTimeFromFile() {
        std::fstream timefile;
        timefile.open("timelog.txt");
    
        if(!timefile.is_open()) {
            qDebug() << "File not opening";
        }
    
        std::string thetime;
        std::getline(timefile, thetime);
        timefile.close();
        return thetime;
    
    }
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        std::string timeToDisplay = readTimeFromFile();
    }
    
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    

    I assume it's because of the directory where the compiled program ends up and have looked at supposed solutions to this online but some seem so complex that I'd rather get a solid answer before I proceed. Thanks for any help.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Where is that file located ?
    Any reason for the path to be hardcoded ?
    What will be its use ?



  • @sgaist Hey and thank you. I added a new file via right-clicking the sources folder and adding the text file that way. The directory is: C:\Users\Byte\Documents\testProg (testProg is the name of the project, pretty bad). The file is just going to keep track of a time. It's an eternal stopwatch. An example use case:

    1. I load the program up, the label is set to the time stored in the file.
    2. I exit the program, the time elapsed is added to the original time and is written back to the file.

  • Lifetime Qt Champion

    In that case, use QStandardPaths to get a suitable location for your application data and put the file there.



  • @sgaist I used the method and got a filepath returned however the directory returned doesn't actually exist?



  • Ah, figured it out. Thanks for the help.


Log in to reply