Important: Please read the Qt Code of Conduct -

Get an FileError(5) when i use QFile object to open a txt file at second time

  • QFile object returns error when i use it to open a txt file, (the errorString() returns: system cannot find specific path in chinese) ps: my code was copied from the qt document samples.

    Here is my code, hope someone can help me out!

    //declare in header file CommonHelper.h
    static QString readTextFile(QString name);

    //implementation in CommonHelper.cpp file
    QString CommonHelper::readTextFile(QString name){
    QString data;
    QFile f(name);
    if(! | QIODevice::Text)){
    return data; //always get errors when call this function at second time!!(ps: the errorString() returns: system cannot find specific path in chinese)
    QTextStream in(&f);
    data = in.readAll();

    return data;


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Are you reading the same file again ?

    If not, are you sure that the file given exists ?

  • yes, i'm reading the same file(it's a html template for printing), and i'm sure the file exists. in my program, click the button twince, it works just at first time click.

  • Lifetime Qt Champion

    Then can you show the code where you use readTextFile ?

  • Below is the code used to call method readTextFile(QString str):

    @bool PrintableHistoryObject::printing(){
    //get template
    QString strTemplate = CommonHelper::readTextFile(AppDef::SYS_HISTORY_TEMPLATE_FILE_NAME);
    return false; //the value of strTemplate will be set to empty string at second time call
    //replace parameters
    strTemplate = strTemplate.replace("[seqNum]", seqNum.isEmpty()?"":seqNum);

    //other source codes was omitted


  • Lifetime Qt Champion


  • it's a static variable QString:


    @QString AppDef::SYS_HISTORY_TEMPLATE_FILE_NAME = "data/historyTemplate.htm";@

  • Lifetime Qt Champion

    Using a relative path can be dangerous, if this file is always in the same place you should use an absolute path. You could be changing something somewhere in your software like the current working directory and then your file will not be found.

  • understood. thank you very much! I'll try this in my program.

Log in to reply