虽然文件包含数据,但QT不加载文件数据

虽然文件包含数据,但QT不加载文件数据,qt,file,Qt,File,我尝试将CSV文件加载到“QString”中(以便将来将其转换为html文件) 但是,尽管文件存在并包含数据,但QT“认为”该文件是空的 这是我的职责: void readCSVfile(QString csvFileName, bool relativePath) { QString csvFile = csvFileName; QString workingDir = QDir::currentPath() + "//"; QString fullCSVpath =

我尝试将CSV文件加载到“QString”中(以便将来将其转换为html文件)

但是,尽管文件存在并包含数据,但QT“认为”该文件是空的

这是我的职责:

void readCSVfile(QString csvFileName, bool relativePath)
{
    QString csvFile = csvFileName;
    QString workingDir = QDir::currentPath() + "//";

    QString fullCSVpath = (relativePath ? workingDir : "") + csvFile;
    QFile csvfile(fullCSVpath);

    // verify csv file is exist
    if (!csvfile.exists())
    {
        csvfile.close();
        return;
    }

    QTextStream in(&csvfile);
    // test - to verify QT success to read the file.
    QString alltextTemp = in.readAll();
}
QFile csvfile(fullCSVpath);

if ( !csvfile.open( QIODevice::ReadOnly ) )
{
    Log( tr("Could not read file %1: %2") .arg( csvfile ) .arg( csvfile.errorString() );
    return false;
}

QTextStream in(&csvfile);
这是我的文件内容:

Time,Reporter,Type,Content,Screenshot,RTF Note
11/12/2013 5:37:25 PM,Asf,(Rapid Reporter version),"1.12.12.28",,
11/12/2013 5:37:25 PM,Asf,Session Reporter,"Asf",,
11/12/2013 5:37:25 PM,Asf,Session Charter,"target",,
11/12/2013 5:37:47 PM,Asf,Session End. Duration,"00:00:22",,
问题:“alltextTemp”变量包含空字符串(不包含文件内容)

问题是:为什么?(或者我需要做什么才能获得内容)

该文件没有特殊权限等

QT 5.1.1

操作系统:Win7x64


谢谢你的帮助

仅用文件名初始化QFile对象是不够的。这并不能告诉Qt您正试图对此文件执行什么操作(您是否正在尝试打开现有文件?创建新文件?删除现有文件?)。这也不允许Qt立即告诉您它无法打开文件,因为构造函数无法返回值,并且Qt不使用异常

要实际打开文件进行读取,需要调用
open
成员函数:

void readCSVfile(QString csvFileName, bool relativePath)
{
    QString csvFile = csvFileName;
    QString workingDir = QDir::currentPath() + "//";

    QString fullCSVpath = (relativePath ? workingDir : "") + csvFile;
    QFile csvfile(fullCSVpath);

    // verify csv file is exist
    if (!csvfile.exists())
    {
        csvfile.close();
        return;
    }

    QTextStream in(&csvfile);
    // test - to verify QT success to read the file.
    QString alltextTemp = in.readAll();
}
QFile csvfile(fullCSVpath);

if ( !csvfile.open( QIODevice::ReadOnly ) )
{
    Log( tr("Could not read file %1: %2") .arg( csvfile ) .arg( csvfile.errorString() );
    return false;
}

QTextStream in(&csvfile);
请注意,打印描述性错误消息是一种良好的编程实践,因此应用程序的用户知道:

  • 试图打开哪个文件
  • 您试图对文件执行什么操作(读取?写入?创建?)
  • 文件无法打开的原因

使用qDebug语句打印fullCSVpath,查看它是否是您想要的文件路径,以及我看到的一个小故障,但我不确定它是否会导致您遇到的问题:“/”-斜杠不需要转义,一个斜杠就够了(只需要转义反斜杠字符)请记住,默认文件夹可能不是包含可执行文件的文件夹。对于Visual Studio,调试时的默认文件夹是包含解决方案文件的文件夹。另外,我希望您在其他地方设置alltextTemp,因为它将在下一个}时超出范围。您需要打开()该文件。如果文件不存在,open()将失败,无需关闭。要进行进一步调试,请检查所有返回值(open()),并在出现错误时检查csvfile.errorString()。