QT系列第9节 文件目录操作

QT编程中,文件目录操作很常见,现在就将常用的文件目录操作做一个总结。

1.文件操作

QFile支持文本文件和二进制文件的操作,主要接口如下:

qint64 read( char * data, qint64 maxSize);

QByteArray read( qint64 maxSize);

QByteArray readAll();

QByteArray readLine();

qint64 write(const char * data, qint64 maxSize);

qint64 write(const QByteArray & byteArray);

QT为了简化文本文件和数据文件的读写操作,提供了QTextStream和QDataStream两个辅助类

QTextStream可将写入的数据全部转换为可读文本,QDataStream可将写入的数据根据类型转换为二进制数据。

QFile的open()函数打开文件时,参数QIODevice::OpenModeFlag取值如下:

QIODevice::ReadOnly:以只读方式打开文件,用于载入文件。

QIODevice::WriteOnly:以只写方式打开文件,用于保存文件。

QIODevice::ReadWrite:以读写方式打开。

QIODevice::Append:以添加模式打开,新写入文件的数据添加到文件尾部。

QIODevice::Truncate:以截取方式打开文件,文件原有的内容全部被删除。

QIODevice::Text:以文本方式打开文件,读取时“\n”被自动翻译为换行符,写入时字符串结束符会自动转换为系统平台的编码,如 Windows 平台下是“\r\n”。

QFileInfo获取文件信息,主要接口如下:

QDir dir() const

bool exists() const

QString fileName() const

QString

filePath() const

QString

group() const

uint

groupId() const

bool

isAbsolute() const

bool

isBundle() const

bool

isDir() const

bool

isExecutable() const

bool

isFile() const

bool

isHidden() const

bool

isNativePath() const

bool

isReadable() const

bool

isRelative() const

bool

isRoot() const

bool

isSymLink() const

bool

isWritable() const

QDateTime

lastModified() const

QDateTime

lastRead() const

bool

makeAbsolute()

QString

owner() const

uint

ownerId() const

QString

path() const

bool

permission(QFile::Permissions permissions) const

QFile::Permissions

permissions() const

1.1 文本文件操作

方法一:

void writeTxtFile_1(const QString& inputFileName) {
    QFile file(inputFileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return;
    }

    QString str = "hello world, this is qt programme\n";
    QByteArray  strBytes = str.toUtf8();
    file.write(strBytes, strBytes.length());

    str = "hello China\n";
    strBytes = str.toUtf8();
    file.write(strBytes, strBytes.length());

    str = "hello dagongren\n";
    strBytes = str.toUtf8();
    file.write(strBytes, strBytes.length());

    file.close();
}

void readTxtFile_1(const QString& inputFileName) {
    QString fileName = inputFileName;
    QFile objFile(fileName);
    if (!objFile.exists()) {
        qDebug() << "file " << fileName << " not exists" << endl;
        return;
    }
    if(!objFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        qDebug() << "open " << fileName << " error" << endl;
        return;
    }
    qDebug() << "file size: " << QString::number(objFile.size()) << endl;
    qDebug() << "file attr: " << QString::number(objFile.permissions(), 16) << endl;

    QString lineText = objFile.readLine();
    qDebug() << "lineText: " << lineText << endl;

    QString allText = objFile.readAll();
    qDebug() << "allText: " << allText << endl;

    objFile.close();
}

方法二:

void writeTxtFile_2(const QString &fileName)
 {
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
      return;
    }

    QTextStream textStream(&file);

    QString str = "11111111111111111111111";
    textStream << str << '\n';
    str = "222222222222222222222";
    textStream << str << '\n';
    str = "3333333333333333333333";
    textStream << str << '\n';
    str = "4444444444444444444";
    textStream << str << '\n';

    file.close();
}

void readTxtFile_2(const QString &fileName)
{
    QFile file(fileName);

    if (!file.exists())
    {
    return;
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    return;
    }

    QTextStream textStream(&file);
    QString lineText = textStream.readLine();
    qDebug() << "lineText: " << lineText << endl;
    lineText = textStream.readLine();
    qDebug() << "lineText: " << lineText << endl;
    QString leftTxt = textStream.readAll();
    qDebug() << "leftTxt: " << leftTxt << endl;

    file.close();
}

1.2 二进制文件操作

// 写二进制文件
void writeBinFile_1(const QString &fileName) {
    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly)) {
        qDebug() << "open file " << fileName << " error" << endl;
        return;
    }
    QDataStream out(&file);
    out << 9527 << QByteArray("我爱你,中国!");
    file.close();
}

//读二进制文件
void readBinFile_1(const QString &fileName) {
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "open file " << fileName << " error" << endl;
        return;
    }
    QDataStream in(&file);
    int n;
    QByteArray s;
    in >> n >>  s;
    file.close();
    qDebug() << n << " " << s.toStdString().c_str();
}

2.目录操作

QDir:用于对目录的操作,参数为空默认是当前可执行程序路径

QDir支持过滤器操作,取值如下:

QDir::AllDirs: 列出所有目录名

QDir::Files: 列出所有文件

QDir::Drives: 列出所有盘符(Unix系统下无效)

QDir::NoDotAndDotDot: 不列出特殊的符号,如".",".."

QDir::AllEntries: 列出目录下所有项目

void testDirOper() {
    QDir dir(QDir::current()); // QDir dir;
    foreach (QFileInfo mItem, dir.entryInfoList()) {
        if(mItem.isDir()) {
            qDebug() << "Dir: " << mItem.filePath();
        }
        else {
            qDebug() << "File: " << mItem.filePath();
        }
    }

    /*
    QDir::AllDirs: 列出所有目录名
    QDir::Files: 列出所有文件
    QDir::Drives: 列出所有盘符(Unix系统下无效)
    QDir::NoDotAndDotDot: 不列出特殊的符号,如".",".."
    QDir::AllEntries: 列出目录下所有项目
    */
    //过滤器的使用
    QDir tDir(QDir::current());
    QStringList filters;
    //只过滤出.o和.txt的文件
    filters << "*.o" << "*.txt";
    tDir.setNameFilters(filters);
    qDebug() << tDir.entryList(filters, QDir::AllEntries);

    qDebug() << QDir::tempPath() << endl;
    qDebug() << QDir::rootPath() << endl;
    // qDebug() << QDir::homePath() << endl;
    qDebug() << QDir::currentPath() << endl;
}

3.文件目录监控

QT支持文件目录的监控操作,使用类QFileSystemWatcher即可监控文件和目录的变化

cusesignalandslot.h

#ifndef CUSESIGNALANDSLOT_H
#define CUSESIGNALANDSLOT_H

#include <QDir>
#include <QTemporaryDir>
#include <QTemporaryFile>
#include <QObject>
#include <QFileSystemWatcher>


class CUseSignalAndSlot : public QObject {

    Q_OBJECT
public:
    CUseSignalAndSlot();
    virtual ~CUseSignalAndSlot();
    void setFileWatch();
    void setDirWatch();


signals:
    void stringChanged(QString str);
    void intChanged(int ivalue);
    void doubleChanged(double dvalue);

public slots:
    void setString(QString str);
    void setInt(int ivalue);
    void setDouble(double dvalue);
    void onFileChanged(QString path);
    void onDirChanged(QString path);

private:
    QString m_str;
    int m_ivalue;
    double m_dvalue;
    QFileSystemWatcher  m_fileWatcher;
};

#endif // CUSESIGNALANDSLOT_H

cusesignalandslot.cpp

#include "cusesignalandslot.h"
#include <QDebug>

CUseSignalAndSlot::CUseSignalAndSlot()
{

}

CUseSignalAndSlot::~CUseSignalAndSlot() {
}

void CUseSignalAndSlot::setFileWatch() {
    QString file = QDir::current().absolutePath();
    file += "/watch.txt";
    m_fileWatcher.addPath(file);
    connect(&m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &CUseSignalAndSlot::onFileChanged);
}

void CUseSignalAndSlot::setDirWatch() {
    m_fileWatcher.addPath(QDir::current().absolutePath());
    connect(&m_fileWatcher, &QFileSystemWatcher::directoryChanged, this, &CUseSignalAndSlot::onDirChanged);
}

void CUseSignalAndSlot::setString(QString str) {
    m_str = str;
}

void CUseSignalAndSlot::setInt(int ivalue) {
    m_ivalue = ivalue;
}

void CUseSignalAndSlot::setDouble(double dvalue) {
    m_dvalue = dvalue;
}

void CUseSignalAndSlot::onFileChanged(QString path) {
    qDebug() << "file: " << path << " changed !";
}

void CUseSignalAndSlot::onDirChanged(QString path) {
    qDebug() << "dir: " << path << " changed !";
}

4.临时文件和目录操作

临时文件目录操作主要类:QTemporaryDir,QTemporaryFile

4.1临时目录

void testTempDir() {
    QTemporaryDir testdir1;
    qDebug() << testdir1.autoRemove() << testdir1.filePath("myuse.txt");
    QTemporaryDir testdir3("tes_tdir");
    qDebug() << testdir3.autoRemove() << "  " << testdir3.path() << endl;
    qDebug() << testdir3.autoRemove() << "  " << testdir3.filePath("hello.txt") << endl;
}

4.2临时文件

void testTempFile() {
    //匿名临时文件
    QTemporaryFile tempFile1;
    qDebug() << "tempFile1: "<< tempFile1.fileName() << " " << tempFile1.fileTemplate();

    tempFile1.open();
    tempFile1.close();
    qDebug() << "tempFile1: " << tempFile1.fileName() << " " << tempFile1.fileTemplate();

    tempFile1.open();
    qDebug() << "tempFile1: " << tempFile1.fileName() << " " << tempFile1.fileTemplate();


    //命名临时文件
    QTemporaryFile tempFile2("tempFile2");
    tempFile2.open();
    qDebug()<<"tempFile2: "<< tempFile2.fileName() << " " << tempFile2.fileTemplate();
    //建立一个重名的,注意:命名临时文件建立在可执行程序目录下
    QTemporaryFile tempFile3("tempFile3");
    tempFile3.open();
    qDebug()<<"tempFile3: " << tempFile3.fileName() << " " << tempFile3.fileTemplate();

    //在QTemporaryDir临时目录下建立一个
    QTemporaryDir tempdir1;
    qDebug()<<"tempdir1: " << tempdir1.filePath("tempFile4.txt");
    QTemporaryFile tempFile4(tempdir1.filePath("tempFile4.txt"));
    tempFile4.open();
    qDebug()<<"tempFile4: " << tempFile4.fileName() << " " << tempFile4.fileTemplate();
}

5.应用程序路径

应用程序所在路径获取:

void showAppFileDir(const QCoreApplication& a) {
    qDebug() << "应用程序完整路径:: " << a.applicationFilePath() << endl;
    qDebug() << "应用程序所在目录:: " << a.applicationDirPath() << endl;
    qDebug() << "应用程序名:: " << a.applicationName() << endl;
}

猜你喜欢

转载自blog.csdn.net/hsy12342611/article/details/128574474