QFile
QFile
类提供了对文件的低级访问,可以用于读写文件,支持二进制和文本文件。
- open(): 打开文件,参数为
QIODevice::OpenMode
模式,如QIODevice::ReadOnly
或QIODevice::WriteOnly
。 - close(): 关闭文件。
- readAll(): 读取文件的全部内容。
- write(): 写入数据到文件。
- flush(): 刷新文件,将缓冲区中的数据写入磁盘。
- size(): 返回文件的大小。
- rename(): 重命名文件。
- remove(): 删除文件。
- exists(): 检查文件是否存在。
以下是QIODevice::OpenMode
中常见的几种模式,以及它们的含义:
-
QIODevice::NotOpen - 文件没有打开。
-
QIODevice::ReadOnly - 文件以只读模式打开。
-
QIODevice::WriteOnly - 文件以只写模式打开。
-
QIODevice::ReadWrite - 文件以读写模式打开。
-
QIODevice::Append - 文件在追加模式下打开,所有的写操作都会追加到文件的末尾。如果文件不存在,它会被创建。
-
QIODevice::Truncate - 如果与写模式(
WriteOnly
或ReadWrite
)结合使用,文件在打开时会被截断至零长度。如果文件不存在,它会被创建。 -
QIODevice::Unbuffered - 文件以无缓冲模式打开,所有数据立即写入或从磁盘读取。
-
QIODevice::Unbuffered - 文件以无缓冲模式打开,所有数据立即写入或从磁盘读取。
-
QIODevice::Text - 表示设备将用于文本数据传输,行结束符将被转换成平台特定的格式。
QIODevice::Append
作为QFile::open()
方法的参数之一时,它意味着任何写入操作都将发生在文件的末尾
QIODevice::Append | QIODevice::Text
:以追加模式打开文本文件。QIODevice::Append | QIODevice::Unbuffered
:以追加模式打开,禁用缓冲区,直接写入磁盘。- QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text 确保每次打开文件时,其内容都被清空。
读内容
void Widget::readFileContent()
{/
QString filePath = QString("D:/a.txt");
QFile file(filePath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
QString a;
a = stream.readAll();
qDebug()<<"=======a"<<a;
}
}
//读行
QFile file("path/to/file.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
qDebug() << line;
}
file.close();
}
写内容
QString filePath = QString("D:/a.txt");
QFile file(filePath);
//如果文件不存在 会创建 QIODevice::Append对已有内容追加内容
if(file.open(QIODevice::Append |QIODevice::Text)){
return;
}
QTextStream out(&file);
QString content = "sssss";
out<<content;
更新中。。。。。。