【QT学习笔记】QT教程:QFile 用法

QFile 是 Qt 框架中的一个类,用于进行文件操作,如读取、写入、移动、复制和获取文件属性等。以下是一些基本的 QFile 使用方法:

  • 打开文件

#cpp

   QFile file("path/to/your/file.txt"); // 创建一个QFile对象,传入文件路径
   if (file.open(QIODevice::ReadOnly)) { // 打开文件,只读模式
       // 文件打开成功,可以进行读取操作
   } else {
       qDebug() << "Failed to open file: " << file.errorString(); // 如果打开失败,输出错误信息
   }
   
  • 读取文件内容
    • 一次性读取整个文件:

#cpp

     QByteArray data = file.readAll();
     
  • 分步读取:

#cpp

     char buffer[1024];
     qint64 readBytes = file.readLine(buffer, sizeof(buffer));
     while (readBytes > 0) {
         // 处理buffer中的数据
         readBytes = file.readLine(buffer, sizeof(buffer));
     }
     
  • 写入文件

#cpp

   if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { // 打开文件,写入模式,并清空原有内容
       QTextStream out(&file);
       out << "Writing some text to the file...\n";
       // 或者直接使用write函数写入字节数组
       file.write("Some binary data");
       file.close(); // 完成写入后关闭文件
   }
   
  • 文件拷贝

#cpp

   QString oldFilePath = "path/to/oldfile.txt";
   QString newFilePath = "path/to/newfile.txt";
   if (QFile::copy(oldFilePath, newFilePath)) {
       qDebug() << "File copied successfully.";
   } else {
       qDebug() << "Failed to copy file: " << QFile::errorString();
   }
   
  • 移动或重命名文件

#cpp

   if (file.rename("new/path/to/file.txt")) {
       qDebug() << "File renamed successfully.";
   } else {
       qDebug() << "Failed to rename file: " << file.errorString();
   }
   
  • 获取文件信息

#cpp

   if (file.exists()) {
       quint64 fileSize = file.size();
       QDateTime lastModified = file.lastModified();
       QFile::Permissions permissions = file.permissions();
       // ... 对这些信息进行处理
   }
   

以上代码片段展示了如何使用 QFile 类进行基本的文件操作。在实际应用中,请确保正确处理可能出现的异常情况,例如文件不存在、无法打开或者权限不足等问题。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IIIIIII_II

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值