四时宝库

程序员的知识宝库

Qt 读写txt文本文件(qt读文件操作)

打开文件时,使用参数选择打开文件模式

需要导入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();

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接