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

Read from the file twice



  • Hi,

    i try to do the following

    open a file and read only the first line (which is a piece of information i need for something else), then read the whole content and do something with it (actually need to create a QBuffer but i left it out in the snippet below).

    i had a look around and put together the snippet below which works. But to achieve the task i open the file, close it and then re-open it again. So just wondering if there's a more graceful way to do it.

    QString pathToSomeFile = "/path/to/some/file";
    
    QFile someFile(pathToSomeFile);
    if(!someFile.open(QIODevice::ReadOnly)) return;
    
    QTextStream in(&someFile);
    QString firstLine = in.readLine();
    // do sth with firstLine;
    
    // below i re-open the file as otherwise the content read is blank
    someFile.close();
    if(!someFile.open(QIODevice::ReadOnly)) return;
    
    QByteArray dataFile = someFile.readAll();
    QString wholeContent = QString(dataFile);
    // use  QByteArray to create a QBuffer and do more stuff
    

    Thanks


  • Lifetime Qt Champion

    Hi,

    You can seek back to 0.



  • @luminski said in Read from the file twice:

    So just wondering if there's a more graceful way to do it.

    Are you sure you need a feeform text file? fixed block IO on binary files is much easier to correctly program for.



  • @luminski
    As @SGaist has said, if you really need to re-read an already-opened-and-partially-read file you can seek(0) to accomplish that.

    Alternatively: if the two reading segments of code are "close together", as per the code the show, you could: reverse the order of your operations, read the whole file first and get the first line from what you already read into memory instead of in.readLine(), like:

    if(!someFile.open(QIODevice::ReadOnly)) return;
    
    QByteArray dataFile = someFile.readAll();
    QString wholeContent = QString(dataFile);
    someFile.close();
    
    QString firstLine = wholeContent.split("\n").at(0);
    

Log in to reply