Qt文件操作之一QFile(使用QTextStream读取文件)

Qt文件操作之一QFile(使用QTextStream读取文件)

1 QFile介绍

The QFile class provides an interface for reading from and writing to files. More…

Header: #include
qmake: QT += core
Inherits: QFileDevice
Inherited By: QTemporaryFile

List of all members, including inherited members
Obsolete members
Note: All functions in this class are reentrant.

QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.
The file name is usually passed in the constructor, but it can be set at any time using setFileName(). QFile expects the file separator to be ‘/’ regardless of operating system. The use of other separators (e.g., ‘’) is not supported.
You can check for a file’s existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)
The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.
The size of the file is returned by size(). You can get the current file position using pos(), or move to a new file position using seek(). If you’ve reached the end of the file, atEnd() returns true.
Reading Files Directly
The following example reads a text file line by line:

      QFile file("in.txt");
      if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
          return;

      while (!file.atEnd()) {
          QByteArray line = file.readLine();
          process_line(line);
      }

The QIODevice::Text flag passed to open() tells Qt to convert Windows-style line terminators ("\r\n") into C+±style terminators ("\n"). By default, QFile assumes binary, i.e. it doesn’t perform any conversion on the bytes stored in the file.
Using Streams to Read Files
The next example uses QTextStream to read a text file line by line:

QFile file("in.txt");
      if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
          return;

      QTextStream in(&file);
      while (!in.atEnd()) {
          QString line = in.readLine();
          process_line(line);
      }

QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system’s local 8-bit encoding is used (e.g., UTF-8 on most unix based operating systems; see QTextCodec::codecForLocale() for details). This can be changed using QTextStream::setCodec().
To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right:

QFile file("out.txt");
      if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
          return;

      QTextStream out(&file);
      out << "The magic number is: " << 49 << "\n";

QDataStream is similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.

Qt 使用 QFile 和 QDataStream 进行二进制数据文件的读写:
QFile 负责文件的 IO 设备接口,即与文件的物理交互;
QDataStream 以数据流的方式读取文件内容或写入文件内容。

QDataStream提供了基于QIODevice的二进制数据的序列化。数据流是一种二进制流,这种流完全不依赖于底层操作系统、CPU 或者字节顺序(大端或小端)。例如,在安装了 Windows 平台的 PC 上面写入的一个数据流,可以不经过任何处理,直接拿到运行了 Solaris 的 SPARC 机器上读取。由于数据流就是二进制流,因此我们也可以直接读写没有编码的二进制数据,例如图像、视频、音频等。

QDataStream既能够存取 C++ 基本类型,如 int、char、short 等,也可以存取复杂的数据类型,例如自定义的类。实际上,QDataStream对于类的存储,是将复杂的类分割为很多基本单元实现的。

2 文本文件的读写操作

2.1 文本文件读取

文件可以用open()来打开、用close()来关闭、用flush()来刷新。数据通常可以使用QDataStream或者QTextStream进行读写,但你也可以使用read(),readLine(),readAll(),write()读写。QFile也支持getChar(),putChar(),和ungetChar()
size()可以返回文件的大小。你可以通过使用pos()函数得到当前文件位置或者使用seek()移到一个新的文件位置。如果你到了文件的末尾,atEnd()返回真,一行一行直接读取文件。

二进制文件的读写文件可以使用QFile类、QDataStream
文本文件的读写建议使用QTextStream类,它操作文件更加方便。
打开文件时,需要参数指定打开文件的模式:
在这里插入图片描述

使用Qt的QFileDialog类,实现文件选择对话框多选文件的功能,参考Qt官方文档根据上边的库文件程序与getOpenFileName()函数我们可以在资源管理器中查看文件,获取以“.txt”文件为后缀的文件目录路。

bool MainWindow::openFidFile(QString path)
{
    Q_UNUSED(path);
    fileName = QFileDialog::getOpenFileName(this, tr("选择历史谱图文件"),"",tr("TXT(*.txt)")); //选择路径
    if(fileName.isEmpty()) //如果未选择文件便确认,即返回
        return false;
    QFile file(fileName);
    if(!file.open((QIODevice::ReadOnly | QIODevice::Text))){
        qDebug()<<"Can't open the file!"<<endl;
        return false;
    }

    //使用QTextStream读取文件
    QTextStream in(&file);
    QString line = in.readLine();
    QStringList list = line.split(',');

    quint32 count = 0;
    qDebug()<<"num: "<<count++<<", "<<line;
    while (!line.isNull()) {
        line = in.readLine();
        list = line.split(',');
        qDebug()<<"num: "<<count++<<", "<<line;
    }

    file.close();

    return true;
}

2.2 文本文件写入

QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    file.close();
    if (file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        QTextStream stream(&file);
        stream.seek(file.size());

        stream << write_txt << "\n";
        file.close();
    }

文本文件写入主要依靠使用QTextStream 类来对文件进行读取。其中使用WriteOnly函数对文件进行清空,防止文件累计存入。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值