-1

I'm using Qt for a project. I'll constanly read from a file with read from unistd.h, but how can i do that? I have tried to use an infinite while loop but my application crash when i do that.

PS i'm beginner when it comes to Qt and fileoperation (unistd.h).

int fd;
char c;

fd = open("/home/stud/txtFile", O_RDWR);//open file
if(fd == -1)
    cout << "can't open file" << endl;

read(fd, (void*)&c, 1);

if(c == '1')
    //do stuff
else
    //do stuff
László Papp
  • 51,870
  • 39
  • 111
  • 135
Loc Dai Le
  • 1,661
  • 4
  • 35
  • 70
  • 1
    Why are you using `unistd.h` to read files if you're using Qt? Qt comes with a set of platform-independent file operations. – Matti Virkkunen Oct 26 '14 at 00:37
  • I'm using Qt in linux on a beagleboard with an lcd display. I want to read from a device driver file - nod file. – Loc Dai Le Oct 26 '14 at 00:56
  • 1
    You already forgot about [your other question](http://stackoverflow.com/questions/26554879/qt-creator-read-from-a-file-and-print-it-out-on-beaggleboard)? Either way, Qt provides you the async API, whereas you would need to invent it yourself if you do not utilize that. Busy loops are bad. – László Papp Oct 26 '14 at 08:17
  • It is very inefficient to call [read(2)](http://man7.org/linux/man-pages/man2/read.2.html) on a single byte buffer. You should better `read` a buffer of several kilobytes and use the result of `read` (count of actually read bytes) – Basile Starynkevitch Oct 26 '14 at 08:28

1 Answers1

0

If you are forced to use the low level read() then make sure to check for a valid file descriptor before reading.

Your sample code still attempts to read even if open fails.

Change to:

fd = open("/home/stud/txtFile", O_RDWR);//open file
if(fd < 0) {
    cout << "can't open file" << endl;
    // potentially you may want to exit() here
}
else {
    read(fd, (void*)&c, 1);
    // if done with file for this pass, close it. If you need to read again
    // in same program keep it open
    close(fd);
}

Your sample code never closes the file after reading. So I don't know what you mean by "keep reading"; if you mean you open and read with that code over and over without close() then you will eventually run out of descriptors.

codenheim
  • 20,467
  • 1
  • 59
  • 80