【1】修改文件名称
bool RenameFile(QString filePath, QString newName){
QFile file(filePath);
QFileInfo fileInfo(file);
QString path = fileInfo.dir().absolutePath();
QFile fileNew(newName);
QFileInfo fileInfoNew(fileNew);
QString fileExtensionNew = fileInfoNew.suffix();
if (fileExtensionNew .isEmpty()) newName += ".txt"; //限定文件扩展名(例如txt)
if (file.exists()) {
if (file.rename(path + "/" + newName)) {
return true;
}
}
else
{
qDebug()<<"原文件不存在";
return false;
}
}
【2】修改目录名称
bool RenameDir(QString filePath, QString newName){
QFile file(filePath);
QFileInfo fileInfo(file);
QString path = fileInfo.dir().absolutePath();
QFile fileNew(newName);
QFileInfo fileInfoNew(fileNew);
QString fileExtensionNew = fileInfoNew.suffix();
if (fileInfo.isDir())
{
if (!fileExtension.isEmpty())
{
qDebug<<"目录输入格式不正确\n";
return false;
}
if (file.exists()) {
if (file.rename(path + "/" + newName)) {
return true;
}
}
}
}
【3】修改文件只读属性
方法一:
QFileInfo fileInfo(filePath);
if (fileInfo.exists() && fileInfo.isWritable()) {
// 尝试修改文件权限
QFile::setPermissions(fileInfo.absoluteFilePath(), QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup | QFile::ReadOther);
}
方法二:
QProcess process;
#ifndef _Linux
#define _Linux
process.start("attrib +R \"" + filePath + "\"");
#endif
process.start("chmod a-w " + filePath);
process.waitForFinished();