使用QFile類進行讀寫,使用Open函數打開文件,打開方式有:
QIODevice::NotOpen 0x0000 不打開
QIODevice::ReadOnly 0x0001 只讀方式
QIODevice::WriteOnly 0x0002 只寫方式,如果文件不存在則會自動創(chuàng)建文件
QIODevice::ReadWrite ReadOnly | WriteOnly 讀寫方式
QIODevice::Append 0x0004 此模式表明所有數據寫入到文件尾
QIODevice::Truncate 0x0008 打開文件之前,此文件被截斷,原來文件的所有數據會丟失
QIODevice::Text 0x0010 讀的時候,文件結束標志位會被轉為’\n’;寫的時候,文件結束標志位會被轉為本地編碼的結束為,例如win32的結束位’\r\n’
QIODevice::UnBuffered 0x0020 不緩存
第一種辦法:QFile類的iodevice讀寫,即調用QIODevice類的函數
讀:read、readall函數
寫:write函數
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
//創(chuàng)建 QFile 對象,同時指定要操作的文件
QFile file("D:/demo.txt");
//對文件進行寫操作
if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
qDebug()<<"文件打開失敗";
}
//向文件中寫入兩行字符串
file.write("C語言中文網\n");
file.write("http://c.biancheng.net");
//關閉文件
file.close();
//重新打開文件,對文件進行讀操作
if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
qDebug()<<"文件打開失敗";
}
//每次都去文件中的一行,然后輸出讀取到的字符串
char * str = new char[100];
qint64 readNum = file.readLine(str,100);
//當讀取出現錯誤(返回 -1)或者讀取到的字符數為 0 時,結束讀取
while((readNum !=0) && (readNum != -1)){
qDebug() << str;
readNum = file.readLine(str,100);
}
file.close();
return 0;
}
第二種辦法:QFile + QTextStream 結合
讀:readall、readline
寫:<<文章來源:http://www.zghlxwxcb.cn/news/detail-498578.html
寫文件文章來源地址http://www.zghlxwxcb.cn/news/detail-498578.html
void writeTxt()
{
// 文件位置
QFile file("test.txt");
if(!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
{
return;
}
// 文件流
QTextStream stream(&file);
// 輸入內容
stream << "你好";
stream << "111";
file.close();
}
std::vector<QString> readTxt()
{
// 返回值
std::vector<QString> strs;
// 讀取文件位置
QFile file("test.txt");
if(!file.open(QIODevice::ReadOnly))
{
return strs;
}
// 文件流
QTextStream stream(&file);
// 一行一行的讀
while(!stream.atEnd())
{
QString line = stream.readLine();
strs.push_back(line);
}
file.close();
return strs;
}
到了這里,關于qt讀寫文本文件的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!