Qt读取txt及csv文件

2023-12-22 07:29:26

.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QDebug>
#include<QFile>
#include<QTextCodec>
#include<QTextStream>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    写入txt
    QFile file("D:\\Qt_Project\\fileopera\\demo.txt");
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
        qDebug()<<"文件打开失败"<<endl;
    }
    file.write("小鸡咯咯哒\ngys\n您好!");
    file.write("1234567");
    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();


   写入CSV
   QFile file1("D:\\Qt_Project\\fileopera\\test1.csv");
   if( !file1.open( QIODevice::ReadWrite )) {
       return;
   }

   QTextStream out( &file1 );

   QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");

   out<< utf8->toUnicode( "测试1,测试2,测试3\n" );
   out<< utf8->toUnicode( "测试4,测试5,测试6\n" );

   out.flush();
   file1.close();



   读取CSV
   QFile file2("D:\\Qt_Project\\fileopera\\test1.csv");
   if( !file2.open( QIODevice::ReadWrite )) {
       return;
   }

   QTextStream in( &file2 );

   QTextCodec *utf8 = QTextCodec::codecForName( "UTF-8" );

   QList<QStringList> fileDataList;

   while( !in.atEnd() ) {
       QString data = utf8->fromUnicode( in.readLine() );
       QStringList dataList = data.split(",");
       fileDataList.append( dataList );
   }
   qDebug()<< fileDataList;

   file2.close();


}

Widget::~Widget()
{
    delete ui;
}

文章来源:https://blog.csdn.net/weixin_44720592/article/details/135142941
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。