8

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");
Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
Jjreina
  • 2,633
  • 6
  • 33
  • 54

3 Answers3

13

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)

Étienne
  • 4,773
  • 2
  • 33
  • 58
Michal Fapso
  • 1,242
  • 1
  • 15
  • 21
7

I think you already know that you have the various open, read, etc. methods in QFile. That said, if the file is not opened, then the handle method returns an error.

QFile myFile("goforward.raw");
myFile.open(QIODevice::ReadOnly);
int fileHandle = myFile.handle();

After that, you might reopen it with:

FILE* fh = fdopen(fileHandle, "rb");
vulkanino
  • 9,074
  • 7
  • 44
  • 71
-1

If you have the file name, why don't you simply use

QFile *file = fopen(filename.toLocal8Bit().data(), "rb");

?

Isn't it way simpler than creating the QFile, opening it, retrieving the handle, etc.?

And it is pretty bug-free...

andrewsi
  • 10,807
  • 132
  • 35
  • 51
  • This doesn't compile: "error: cannot convert ‘FILE* {aka _IO_FILE*}’ to ‘QFile*’ in initialization" – Étienne Sep 16 '16 at 11:22