/**
* @description: 文件信息
* @param {type}
* @return:
*/
void file_info()
{
QFileInfo info = QFileInfo("filePath"); // 获取路径
QString file_name = info.fileName(); // 文件名
QString file_suffix = info.suffix() // 文件后缀
QString path = info.absolutePath(); // 绝对路径
int size = info.size(); // 大小
}
/**
* @description: 读文件
* @param {type}
* @return:
*/
static QString readFile(const QString &filePath) {
QString line = "";
QFile file(filePath);
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
while (!in.atEnd()) {
line = in.readLine();
}
file.close();
}
return line;
}
/**
* @description: 写文件
* @param {type}
* @return:
*/
static void writeFile(const QString &filePath, const QString &str) {
QFile file(filePath);
if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
out << str << "\n";
file.close();
}
}
/**
* @description: 读文件
* @param {type}
* @return:
*/
static QString readFile2(const QString &filePath) {
QString line = "";
QFile file(filePath);
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
file.readAll();
file.close();
}
return line;
}
/**
* @description: 写文件
* @param {type}
* @return:
*/
static void writeFile2(const QString &filePath, const QString &str | QIODevice::Append) {
QFile file(filePath);
if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
file.write(str.toUtf8());
file.close();
}
}
/**
* @description: 文件是否存在
* @param {type}
* @return:
*/
static bool is_file_exits(const QString &filePath){
QFileInfo fileInfo(filePath);
return fileInfo.isFile();
}
/**
* @description: 创建文件
* @param {type}
* @return:
*/
static void create_file(const QString &filePath) {
if(is_file_exits(filePath)) {
QFile file(filePath);
file.open(QIODevice::WriteOnly); // QIODevice::WriteOnly或者QIODevice::ReadWrite,如果文件不存在,就会创建
file.close();
}
}
/**
* @description: 删除文件
* @param {type}
* @return:
*/
static void remove_file(const QString &filePath) {
if(is_file_exits(filePath)) {
QFile::remove(filePath);
}
}
/**
* @description: 创建多级目录
* @param {type}
* @return:
*/
static void create_dir(QString &dirPath) {
if(dirPath.endsWith("/")){
dirPath.chop(1);
}
QDir dir(dirPath);
if(!dir.exists()) {
dir.mkpath(dirPath);
}
}
/**
* @description: 删除目录
* @param {type}
* @return:
*/
static void clear_dir(const QString &dirPath) {
QDir dir(dirPath);
dir.setFilter(QDir::Files);
int fileCount = dir.count();
for (int i = 0; i < fileCount; i++) {
dir.remove(dir[i]);
}
}
/**
* @description: 过滤文件夹下的文件
* @param {type}
* @return:
*/
void find_info()
{
QDir dir;
QStringList filters;
filters << "*.jpg"
<< "*.jpeg"
<< "*.png"; // 设置过滤类型
dir.setNameFilters(filters); // 设置文件名的过滤
QFileInfoList li = dir.entryInfoList();
for (int i = 0; i < li.size(); ++i)
{
qDebug() << li.at(i).fileName();
}
}
读文件
一次性读完
QByteArray data = file.readAll();
一次读一行
QByteArray data;
while(file.atEnd == false) {
data += readLine();
}
Qt:文件操作QFile/QDir
最新推荐文章于 2024-06-25 10:00:00 发布
本文详细介绍使用Qt进行文件和目录操作的方法,包括文件信息获取、读写操作、目录创建与删除,以及文件过滤等实用功能,适用于Qt应用程序开发。
2055

被折叠的 条评论
为什么被折叠?



