对文件的操作最常见的就是文件的读取了,传入一个文件名,要向其中写入数据或者读取数据。QFile类中可以完成于文件操作相关的很多内容。另外还有一个文件读取和写入的辅助的类,即QTextStream。有点类似标准C++中的cout,cin等操作,不过这里的对象是Qt,不是终端。
下面的代码完成向一个文件中写入数据然后又向该文件中读出写入的数据这一功能。且在资源文件中把本工程的工程文件加入其中并且读出来了.
其效果如下:
代码和注释如下:
#include <QCoreApplication> #include <QDebug> #include <QFile> #include <QString> #include <QTextStream> void write(QString file_name) { //以传入的文件名建立一个文件,传入的文件名包含有目录信息在里面 QFile file(file_name); //以只写和文本的方式打开该文件 if(!file.open(QFile::WriteOnly | QFile::Text)) { qDebug () << "Could not open the file by reading"; return; } //out其实是一个缓冲区 QTextStream out(&file); //输出内容到缓冲区 out << "hell world!"; file.flush();//将缓冲区的内容输出的文本 file.close();//关闭文件 } void read(QString file_name) { QFile file(file_name); //以只读和文本的方式打开该文件 if(!file.open(QFile::ReadOnly | QFile::Text)) { qDebug () << "Could not open the file by reading"; return; } QTextStream in(&file); QString text; //in >> text;//如果是用这句的话则只是独到了1句而已,即内容hello text = in.readAll();//这也写可以全部读完 qDebug () << text; file.close();//关闭文件 } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString file_name = "C:/QtTest/file.txt"; write(file_name); // read(file_name); //该句表示从资源文件中读取内容。因为一开始我已经在资源文件中 //添加了qfile.pro文件。 read(":/MyFiles/qfile.pro"); }