QFile
、QDir
和QFileInfo
是Qt5中的基础类。QFile
提供读写文件的接口,QDir
提供对目录结构及其内容的访问,QFileInfo
提供与系统无关的文件信息,包括文件系统中的文件名称和位置,访问时间和修改时间,权限或文件所有权。
文件大小
在这个例子中,我们确定文件的大小。
// file_size.cpp
#include <QTextStream>
#include <QFileInfo>
int main(int argc, char *argv[]) {
QTextStream out(stdout);
if (argc != 2) {
qWarning("Usage: file_size file");
return 1;
}
// 获取第一个参数
QString filename = argv[1];
// 通过QFile类的exist()方法判断文件是否存在
if (!QFile(filename).exists()) {
qWarning("The file does not exist");
return 1;
}
// 创建一个QFileInfo实例
QFileInfo fileinfo(filename);
// siza()方法获取文件大小信息,
qint64 size = fileinfo.size();
QString str = "The size is: %1 bytes";
out << str.arg(size) << endl;
}
输出结果为:
$ ./file_size Makefile
The size is: 48137 bytes
读内容
为了读取文件的内容,我们必须先打开文件以供阅读。然后创建输入文件流;从这个流中读取数据。
// read_file.cpp
#include <QTextStream>
#include <QFile>
int main(void) {
QTextStream out(stdout);
// 创建一个QFile实例
QFile file("colours");
// QFile类的open()方法以只读的方式打开文件
if (!file.open(QIODevice::ReadOnly)) {
qWarning("Cannot open file for reading");
return 1;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
out << line << endl;
}
file.close();
}
该示例从colours
文件中读取数据。该文件包含八种颜色的名称。
QTextStream in(&file);
输入流被创建。QTextStream
接收文件的引用。数据将从这个流中读取。
while (!in.atEnd()) {
QString line = in.readLine();
out << line << endl;
}
在while循环中,我们逐行读取文件直到文件结束。如果没有更多数据要从流中读取,则atEnd()
方法返回true。readLine()
方法从流中读取一行。
输出结果为:
$ ./read_file colours
red
green
blue
yellow
brown
white
black
violet
写文件
为了写入文件,我们以写入模式打开文件,创建一个指向该文件的输出流,并使用写入操作符写入该流。
// write2file.cpp
#include <QTextStream>
#include <QFile>
int main(void) {
QTextStream out(stdout);
// QFile对象通过给定的文件名创建
QString filename = "distros";
QFile file(filename);
// 应用Qfile类的open()方法以只写的方法打开文件
if (file.open(QIODevice::WriteOnly)) {
// 创建一个在文件引用上运行的QTextStream。
// 换句话说,要写入的数据流被导向文件。
QTextStream out(&file);
// 通过<<操作符写数据
out << "Xubuntu" << endl;
out << "Arch" << endl;
out << "Debian" << endl;
out << "Redhat" << endl;
out << "Slackware" << endl;
} else {
qWarning("Could not open file");
}
// 关闭文件
file.close();
}
该示例将五个linux发行版的名称写入名为distros
的文件名。
输出结果为:
$ ./write2file
$ cat distros
Xubuntu
Arch
Debian
Redhat
Slackware
复制文件
当我们复制文件时,我们使用不同的名称或在文件系统的不同位置创建文件的确切复制。
// copy_file.cpp
#include <QTextStream>
#include <QFile>
int main(int argc, char *argv[]) {
QTextStream out(stdout);
// 该程序有两个参数
if (argc != 3) {
qWarning("Usage: copyfile source destination");
return 1;
}
// 获取源文件名字
QString source = argv[1];
// QFile类的exists()方法判断文件是否存在
if (!QFile(source).exists()) {
qWarning("The source file does not exist");
return 1;
}
// 获取目标文件名字
QString destin(argv[2]);
// 源文件使用QFile::copy()方法复制。
// 第一个参数是源文件名,第二个参数是目标文件名。
QFile::copy(source, destin);
}
该示例使用QFile::copy()
方法创建提供的文件的副本。
输出结果为:
$ ./copy_file colours colours2
$ cat colours
red
green
blue
yellow
brown
white
black
violet
$ cat colours2
red
green
blue
yellow
brown
white
black
violet