-1

我正在将 Qt 用于一个项目。我会不断地从 unistd.h 读取的文件中读取,但我该怎么做呢?我试图使用无限的while循环,但是当我这样做时我的应用程序崩溃了。

PS我是Qt和文件操作(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
4

1 回答 1

0

如果您被迫使用低级别的 read() ,请确保在读取之前检查有效的文件描述符。

即使打开失败,您的示例代码仍会尝试读取。

改成:

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);
}

您的示例代码在阅读后永远不会关闭文件。所以我不知道您所说的“继续阅读”是什么意思;如果您的意思是在没有 close() 的情况下一遍又一遍地打开和阅读该代码,那么您最终将用完描述符。

于 2014-10-26T01:12:47.650 回答