如何判断文件是否已经被打开?
在这里通过文件的一些属性实现判断文件是否被打开,通过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;
}
通过调用对结果判断即可。
更多推荐
C++ 判断文件是否被打开,防止重复打开
发布评论