文本文件读写

7 文件系统和文件读写_List

//解决汉字乱码问题
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec); //解决汉字乱码问题

QFile aFile(aFileName);
aFile.open(QIODevice::ReadOnly | QIODevice::Text)
aFile.readAll();//直接打开文本文件
// while (!aFile.atEnd())
// {
// QByteArray line = aFile.readLine();//自动添加 \n
// QString str=QString::fromLocal8Bit(line); //从字节数组转换为字符串
// str.truncate(str.length()-1); //去除结尾增加的空行
// }


//QTextStream aStream(&aFile); //用文本流读取文件
//aStream.readAll()
// while (!aStream.atEnd())
// {
// str=aStream.readLine();//读取文件的一行
// }
aFile.close();

二进制文件读写

7 文件系统和文件读写_字符串_02

7 文件系统和文件读写_文本文件_03

QDataStream aStream(&aFile);
aStream.setVersion(QDataStream::Qt_5_9); //设置版本号,写入和读取的版本号要兼容

//读取保存二进制
aStream.setByteOrder(QDataStream::LittleEndian);//windows平台设置小端
qint16 rowCount,colCount;
aStream.readRawData((char *)&rowCount, sizeof(qint16));
aStream.readRawData((char *)&colCount, sizeof(qint16));

aStream.writeRawData((char *)&rowCount,sizeof(qint16)); //写入文件流

char *buf;
uint strLen; //也就是 quint32
aStream.readBytes(buf,strLen);//同时读取字符串长度,和字符串内容
QString str=QString::fromLocal8Bit(buf,strLen); //可处理汉字处理汉字

QString zhiLiang=aItem->data(Qt::DisplayRole).toString();
btArray=zhiLiang.toUtf8();
aStream.writeBytes(btArray,btArray.length()); //写入长度,uint,然后是字符串,对于字符串,应使用writeBytes()函数,这样可以同时读取字符串长度和字符串内容

文件目录操作

7 文件系统和文件读写_开发语言_04

QString str=QCoreApplication::applicationDirPath();
QString str=QCoreApplication::applicationFilePath();//
QString str=QCoreApplication::applicationName();
QStringList strList=QCoreApplication::libraryPaths();//程序在运行的时候会用到的路径
QString curDir=QDir::currentPath();
QDir::tempPath();
QDir::rootPath();
QDir::homePath();
QDir::currentPath();
QDir::drives();
bool ok= dir.removeRecursively();//删除所有
QString str=dir.absoluteFilePath(fileName);
QFileSystemWatcher fileWatcher;
fileWatcher.addPath(ui->editDir->text());//添加监听目录
fileWatcher.removePath(ui->editDir->text());//停止监听
QStringList strList=fileWatcher.files();//显示监听文件
QStringList strList=fileWatcher.directories();//显示监听目录
connect(&fileWatcher,&QFileSystemWatcher::fileChanged,
this,&Dialog::on_fileChanged);