QFile/FILE* : How to properly close the handle?

1.1k views Asked by At

I need to open files with QFile and QString for multilingual without hair pulling. But I also need to manage the data of those files through the std::stream API. As many suggest, I used std::fstream stdFile(fdopen(qtFile.handle(), mode)); to do so.

However I hit a problem when it recurring operations. After a specific amount of file handling, the application crashes.

The following code can reproduce the crash:

int fileOperationCount = 0;
while (true)
{
    QFile qtFile("plop.txt");
    qtFile.open(QIODevice::ReadOnly);
    std::ifstream file = std::ifstream(fdopen(qtFile.handle(), "rb"));

    if (!file.good())
        throw std::exception();
    file.seekg(0, file.beg);
    if (!file.good())
        throw std::exception(); //Will ALWAYS trigger at fileOperationCount = 509

    qtFile.close();

    fileOperationCount++;
}

The 509th will crash after the seekg. It also happens if I were to manipulate hundreds of different files. It will still crash the 509th time I try to read a file, any file.

Any idea what I'm doing wrong ?

1

There are 1 answers

4
MarcinG On BEST ANSWER
   int fileOperationCount = 0;
    while (true)
    {
        std::ifstream file ("plop.txt",std::ios::in);

        if (!file.good())
            throw std::exception();
        file.seekg(0, file.beg);
        if (!file.good())
            throw std::exception();

        file.close();
        fileOperationCount++;
    }

this version works if the file exists, if it doesn`t file.good() is false due to eof (I think). If you want to use Qt for translation you can use

            std::ifstream file (QObject::tr("plop.txt"),std::ios::in);

or if the function is inside a QObject use just tr("..") for better context.