在QT中读取多个txt文件 [英] reading multiple txt files in QT

查看:551
本文介绍了在QT中读取多个txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Qt中的多个.txt文件中读取数据。这是我怎么做的







I am trying to read data from Multiple .txt files in Qt. This how I am doing it



void MainWindow::on_pushButton_3_clicked()
{

 QString path = "C:/MyDevelopment/readfiles";
 QDir dir(path);



 QStringList filters;
 filters << "*.txt";

 foreach ( QString fileName, dir.entryList(filters, QDir::Files) )
 {

     QFile readFile(fileName);
     if(!readFile.open(QIODevice::ReadOnly | QIODevice::Text ) )
      {
        qDebug("Failed to read file.....");
        //return ;
      }
      QTextStream in(&fileName);
      while (!in.atEnd())
      {
          QString line = in.readLine();
           qDebug() << line;
      }

 }



我在上述文件夹中有4个.txt文件。对于所有文件,我总是收到msg无法读取文件...。

如果有人能突出我做错了什么就会很好


I have 4 .txt file in the mentioned folder. I am always getting msg "Failed to read file.." for all files.
would be nice if someone can highlight what i am doing wrong

推荐答案

我会尝试调用 readfile.errorString() [ ^ ]。


您是否检查了要打开的文件名?



如果这样做,您可能会注意到那些是没有路径的普通文件名。然后 QFile 尝试打开当前目录中的文件,该文件可能不是传递给 QDir 的文件。



要获得带路径的全名,必须使用 QDir :: entryInfoList

Did you checked the file names you are trying to open?

If you do so, you might notice that those are the plain file names without path. Then QFile tries to open the file in the current directory which is probably not the one passed to QDir.

To get the full names with path you must use QDir::entryInfoList:
foreach (QFileInfo fileInfo, dir.entryInfoList(filters, QDir::Files) )
{
    QFile readFile(fileInfo.absoluteFilePath());
    // ...


QString path = "C:/MyDevelopment/readfiles";
    QDir dir(path);
    QStringList filters;
    filters << "*.txt";

    foreach (QFileInfo fileInfo, dir.entryInfoList(filters, QDir::Files))
    {
       QString fileName = fileInfo.absoluteFilePath();
       //qDebug(fileInfo.absoluteFilePath().toLocal8Bit());
       QFile readFile(fileInfo.absoluteFilePath());
       if(!readFile.open(QIODevice::ReadOnly | QIODevice::Text ) )
             {
               qDebug("Failed to read file.....");
               //return ;
             }
             QTextStream in(&fileName);
             while (!in.atEnd())
             {
                 QString line = in.readLine();
                  qDebug() << line;
             }
    }



输出文件路径仍然没有读取文件。我确信我做错了,因为通常......


output is file path still not reading the files. I am sure i am doing something wrong as usuall...

"C:/MyDevelopment/readfiles/fyfile3.txt"


这篇关于在QT中读取多个txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆