【问题标题】:QFile + QTextStream read only part of the fileQFile + QTextStream 只读文件的一部分
【发布时间】:2019-08-01 02:02:06
【问题描述】:

我正在尝试为一个项目制作 .obj 解析器。

我有带有 loaddata 方法的 ObjLoader 类。它会逐行读取文件并根据需要进行解析。

QFile file(sourceFolder+ QString("/") +filename);
file.open(QIODevice::ReadOnly);
QTextStream textStream(&file);

QString currentString;

while (!textStream.atEnd())
    {
        currentString = textStream.readLine();
        //Some code here without closing file(I doublechecked this) 
    }
file.close()

它可以很好地读取前 600 个字符串,但随后意外停止。
它发生在这些字符串上:

v 3.956570 0.532126 0.300000
v 3.958734 0.593226 -0.300000
v 3.958731 0.593220 0.300000
vn 0.0000 -0.0000 1.0000
vn 0.0000 0.0000 -1.0000
vn 0.4852 -0.8744 0.0000

但是当我尝试时

std::cerr " (抱歉,不知道这个用stackoverflow格式化正常怎么写)

对于这些字符串,通过使用在循环中每次递增的索引“int i”,它只给出:

v 3.956570 0.532126 0.300000
v 3.958734 0.593226 -0.300000
v 3.958731 0.593220 0.300000
v

此时它会停止读取文件而不会出现任何错误。看起来内存中的文件到此结束。但它只是 601-st 字符串,当文件有 1100+ 时。

我在文本编辑器中检查了文件中的不可打印符号,但在这部分中没有任何符号。

每次我开始调试这段代码时,它都会做同样的事情——相同的字符串会在相同的符号处停止读取。为什么会发生?

【问题讨论】:

  • 文件的文本编码是什么?如果您不知道,请考虑从QFile 阅读QByteArray 而不是使用QTextStream,因为使用错误的编码会导致有趣的事情......
  • ASCII 文本文件

标签: c++ qt


【解决方案1】:

显然 textStream.atEnd() 是 not always a reliable indicator that you're actually at the end of a stream. 我会尝试 textStream.ReadAll() 看看你是否以这种方式获得整个文件。或者,您可以调用 textStream.readLine() 直到它返回 NULL 并使用它来中断 while 循环:

currentString = textStream.readLine();
while (!currentString.isNull())
    {
        //Some code here without closing file(I doublechecked this) 
        currentString = textStream.readLine();
    }

【讨论】:

  • 这很奇怪。 readAll 真正一次读取所有文件。但对我来说,逐行阅读会更好。 currentString = textStream.readLine() 在 while 循环中给出错误,因为它无法转换为布尔值(它是 QString)。我尝试使用 !((currentString = textStream.readLine()).isEmpty()) 但它给出的结果与 textStream.atEnd() 相同 - 它停在同一个字符串、同一个符号上。
  • @StakanStakan 编辑了我的评论以修复编译错误。 readAll() 是否至少得到整个文件?你也可以试试QFile::readline(char* data, qint64 maxSize)
  • 是的,readAll() 读取所有内容。但这对我来说不是很好的选择。当然,如果没有其他可以使用它,但是使用读取行将是完美的。而 (file.readLine(arr, 128)!=-1) 只读取前 3 行。我不明白为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 2014-07-22
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多