Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert QFile to FILE*

Tags:

c++

file

qt

qfile

Is there another way to convet QFile to File? Different than this:

QFile myFile("goforward.raw");
int FileDescriptor = myFile.handle();
FILE* fh = fdopen(FileDescriptor, "rb");
like image 531
Jjreina Avatar asked Feb 27 '12 13:02

Jjreina


People also ask

What is QFile?

Qfile is a free companion app for QNAP NAS that allows you to browse and manage the files on your NAS using your iPhone or iPad. Prerequisites: - iOS 13 or later. - A QNAP NAS running QTS 4.0 (and above)

What is QFile QT?

QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream. The file name is usually passed in the constructor, but it can be set at any time using setFileName().

How do you write to a text file in Qt?

This can be changed using setCodec(). To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right. In the following code, we open a new file with the given name and write a text into the file.


1 Answers

We had very strange problems with our application and finally traced it to the QFile/fdopen issue:

void foo(QString filename)
{
    QFile qf(filename);
    qf.open(QIODevice::ReadOnly);
    int fd = qf.handle();
    FILE* f = fdopen(fd, "rb");
    // do some stuff with f
    fclose(f); // !!! undefined behaviour !!!
}

The problem with this code is that fclose(f) is called before the QFile object is destroyed, which is the wrong order: QTBUG-20372

...so either destroy the QFile object before calling fclose() or duplicate the file descriptor returned by QFile::handle():

void foo(QString filename)
{
    QFile qf(filename);
    qf.open(QIODevice::ReadOnly);
    int fd = qf.handle();
    FILE* f = fdopen(dup(fd), "rb"); // !!! use dup()
    // do some stuff with f
    fclose(f); // correct
}

P.S.: Those strange problems with our app showed up only on very few systems by a 10 second delay between a return statement at the end of a function and the actual return from that function. It was really weird. So this is an example of an "undefined behaviour" manifested in the real world :o)

like image 115
Michal Fapso Avatar answered Sep 17 '22 18:09

Michal Fapso