Qt写入读取txt文本文件
程序员文章站
2022-03-31 19:17:53
...
打开文件时,使用参数选择打开文件模式
模式 | 值 | 描述 |
---|---|---|
QIODevice::NotOpen | 0x0000 | 不打开 |
QIODevice::ReadOnly | 0x0001 | 只读方式 |
QIODevice::WriteOnly | 0x0002 | 只写方式,如果文件不存在则会自动创建文件 |
QIODevice::ReadWrite | ReadOnly | WriteOnly |
QIODevice::Append | 0x0004 | 此模式表明所有数据写入到文件尾 |
QIODevice::Truncate | 0x0008 | 打开文件之前,此文件被截断,原来文件的所有数据会丢失 |
QIODevice::Text | 0x0010 | 读的时候,文件结束标志位会被转为’\n’;写的时候,文件结束标志位会被转为本地编码的结束为,例如win32的结束位’\r\n’ |
QIODevice::UnBuffered | 0x0020 | 不缓存 |
需要导入QFile和qDebug、QString头文件
写入
覆盖写入
QFile f("D:\\qtManager.txt");
if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
{
qDebug() << ("打开文件失败");
}
QTextStream txtOutput(&f);
QString str = "123";
txtOutput << str << endl;
f.close();
文末写入
QFile f("D:\\qtManager.txt");
if(!f.open(QIODevice::ReadWrite | QIODevice::Append)) //以读写且追加的方式写入文本
{
qDebug() << ("打开文件失败");
}
QTextStream txtOutput(&f);
QString str = "123";
txtOutput << str << endl;
f.close();
读取
QFile f("D:\\qtManager.txt");
if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << ("打开文件失败");
}
QTextStream txtInput(&f);
QString lineStr;
while(!txtInput.atEnd())
{
lineStr = txtInput.readLine();
qDebug() << (lineStr);
}
f.close();
下一篇: PHP检索字符串函数实例用法