Qt中的基本文件操作

常用类:Qfile Qtextstream Qdatastream Qfiledialog Qiodeive

先实例化一个Qfile对象file,file(),括号内为文件名,默认为当前路径。

文件可以用open()来打开、用close()来关闭、用flush()来刷新。

file.open(Qiodeive::readonly)这里是打开方式,当然还有writeonly readwrite等。


QTextCodec *codec = QTextCodec::codecForName("UTF-8"); //支持中文

    QTextCodec::setCodecForCStrings(codec);  

     

    QFile file( );//括号内为文件路径  

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { //这里对文件是否打开成功进行判断

        qDebug()<<"Can't open the file!"<<endl; 

    } 

    while(!file.atEnd()) { //atEnd(),判断文件是否到最后一行

        QByteArray line = file.readLine(); //还有readAll(),read(),等 读取文件的类型为QbyteArray  

        QString str(line); 

        qDebug()<< str; 


使用QtextStream 来进行读文件,写文件

QtextStream out(&file);//对文件进行写入

out<<"hahahahah";

QtextStream in(&file);//对文件进行读取


QtextStreamin(&file);//对文件进行读取

        while( !in.atEnd()){  
            QString line = in.readLine();  
            qDebug() << line;  
        }









你可能感兴趣的:(常用源码)