.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;
}