Qt中的基本文件操作

来源:互联网 发布:c语言获取网页内容 编辑:程序博客网 时间:2024/05/19 02:06

常用类: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);  

     

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

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

        qDebug()<<"Can'topenthefile!"<<endl; 

    } 

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

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

        QStringstr(line); 

        qDebug()<<str; 


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

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

out<<"hahahahah";

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


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

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