C++ 判断文件是否被打开,防止重复打开

如何判断文件是否已经被打开?

在这里通过文件的一些属性实现判断文件是否被打开,通过QFile将文件尝试实现例如linux的move操作和rm -r 的操作,就可以判断是否文件被占用。

首先添加#include"QFile"头文件,再设置全局的判断标志位:
#include <QFile>
#include <QDesktopServices>
#include"qdebug.h"
#include <windows.h>
#include <QDir>
#include"QProcess"
#include"QFile"
enum Except{ EXCEP_ZERO,EXCEP_ONE};

bool fileNoUsed = false;

下面是具体的判断代码:
bool openDocumentation(){
    QString runPath = QCoreApplication::applicationDirPath();       //获取exe路劲。
    QString hglpName = "高质量C++和C编程指南.pdf";
    QString hglpPath = QString("%1/%2").arg(runPath).arg(hglpName);
    QString filePath = "file:///" + hglpPath;   //打开文件夹用filse:///,打开网页用http://
    QString fileName = hglpName;
    QString newName = "./test01/" + hglpName;
    //通过QFile::exists先判断两个文件是否存在
    if(QFile::exists(fileName) && QFile::exists("./test01/")){
        //拷贝需要查看的文件到新目录下
        if(QFile::copy(fileName, newName)){
            //删除旧目录下的文件来判断文件是否被打开
            if(QFile::remove(fileName)){
                fileNoUsed = true;
            }
        }
    }
    //如果文件没有被打开,则执行QDesktopServices::openUrl()打开文件
    if(fileNoUsed){
        QFile::copy(newName, fileName);
        QFile::remove(newName);
        QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    }else{
        QFile::remove(newName);
        qDebug() << "++++++++++++6666666666666 filename No exit or has been open file!+++++++++++++++";
    }
    return fileNoUsed;
}
通过调用对结果判断即可。
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值