QT5(7)文件处理

时间:2021-02-20 23:11:24

文件的读取一般使用QFile或QStream;文件读写一般使用QTextStream.
QIODevice提供给open()函数的标记

IO_Raw 指定直接的(非缓存的)文件访问。
IO_ReadOnly 以只读模式打开文件。
IO_WriteOnly 以只写模式打开文件。
IO_ReadWrite 以读/写模式打开文件。
IO_Append 设置文件索引到文件的末尾。以追加方式写入文件
IO_Truncate 截短文件。
IO_Translate 在MS-DOS、Windows和Macintosh下对文本文件翻译回车和换行。在Unix系统上这个标记无效。使用时请注意,它会把文件中的每一个换行符转换为一组回车换行。如果你写二进制数据的时候,可能会破坏你要写的文件。请不要和IO_Raw组合使用。

一、使用QFile读取

QFile file("a.txt");  //读取相对目录,在调试状态打开时无法读取,但直接打开编译文件exe可以读取
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {   //QIODevice是一个抽象类,不能被实例化。
     while(!file.atEnd()) {  
        QByteArray line = file.readLine();  
        QString str(line);  
    }  
}  

二、使用QTextStream读取写入

    fileUsers = new QFile("users.txt");
    if(fileUsers -> open(QIODevice::ReadOnly| QIODevice::Text)){  
        QTextStream textReadUsers(fileUsers);  //传递地址
        while(!textReadUsers.atEnd()){
            QString temStr = textReadUsers.readLine();
            QString strName = temStr.section(" ",0,0).trimmed();
            listUsers -> insertItem(0,strName);
        }
    }else{
        listUsers -> insertItem(0,"strName");
    }
void MainWindow::renewUsersList(){
    QString name = lineName -> text();
    QString pass = linePass -> text();
    QString conStr = name+" "+pass;
    QFile *file = new QFile(USERSDIR);
    if(file -> open(QIODevice::WriteOnly|QIODevice::Append)){
        QTextStream write(file);
        write<<conStr<<endl;
    }
    file -> close();
}

三、使用QFileSystemWatcher监视文件变化

// 监视文件变化
QFileSystemWatcher watcher;
watcher.addPath(USERSDIR);    //添加监控
watcher.removePath(USERSDIR) ;  //移除监控 
connect(&watcher,SIGNAL(fileChanged(QString)),this,SLOT(USERSDIRchanged()));

四、QDir获取工作目录、QCoreApplication获取文件所在目录

程序的工作目录和程序 所在目录不同。

qDebug()<<"current applicationDirPath: "<<QCoreApplication::applicationDirPath(); //文件所在目录
qDebug()<<"current currentPath: "<<QDir::currentPath();   //程序工作目录

QT5(7)文件处理