QT  - 讨论区

标题:Qt Tutorial 006:使用QFile读写文件

2014年02月19日 星期三 09:12

在Qt中,如果需要顺序读写文本文件,可以使用QTextStream,如果需要随机读写二进制文件,那么可以使用QFile,QFile与C语言标准库的FILE类似,提供read、write、seek等方法。

在官方文档中,对于QFile有如下描述:

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

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.

编程示例如下:

#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QByteArray>
#include <QString>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString filename("C:/Qt/Projects/006_QFile/main.cpp");
    QFile file(filename);
    qDebug() << file.exists() ;
    file.open(QIODevice::ReadOnly);
    auto content=file.readAll();
    qDebug() << content;
    qDebug() << file.size();
    file.close();
    QString testfile="C:/Qt/Projects/006_QFile/test.txt";
    QFile test(testfile);
    test.open(QIODevice::ReadWrite);
    test.write("Hello Qt!\r\n");
    test.write(content);
    test.seek(0);
    test.write("Hello C++\r\n");
    QString testfile2=testfile.replace(".txt",".bak");
    test.copy(testfile2);
    test.remove();
    QFile::remove(testfile2);
    return a.exec();
}

 

参考资料:

https://qt-project.org/doc/qt-5.0/qtcore/qfile.html

 

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号