打开文件时,使用参数选择打开文件模式
需要导入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();