Qt文件操作

功能描述:打开一个文件,将文件内容写入text文本框中。
步骤:
1 获得文件名
使用QFileDialog类的getOpenFileName获得文件名,函数返回QString类型
2 判断text文本框是否为空,使用QTextEidt对象调用document()->isEmpty(),如果文本框为空则返回true
3 使用QFile打开文件
4 使用QTextStream将文件内容写入文本框中。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QPushButton>
#include<QTextEdit>
#include<QWidget>
class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void loadFile(QString);
private:
    QPushButton *pushButton;
    QTextEdit *text;
private slots:
    void ShowOpenFile();

};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include<QHBoxLayout>
#include<QFileDialog>
#include<QFile>
#include<QTextStream>
MainWindow::MainWindow(QWidget *parent)
    :QWidget(parent)
{
    setWindowTitle(tr("文件"));
    pushButton=new QPushButton;
    pushButton->setText(tr("打开"));
    text=new QTextEdit;
    QHBoxLayout *layout=new QHBoxLayout(this);
    layout->addWidget(pushButton);
    layout->addWidget(text);
    connect(pushButton,SIGNAL(clicked(bool)),this,SLOT(ShowOpenFile()));

}
void MainWindow::ShowOpenFile()
{
    QString fileName=QFileDialog::getOpenFileName(this);
    if(!fileName.isEmpty())
    {
        if(text->document()->isEmpty())
        {
            loadFile(fileName);
        }
        else
        {
            MainWindow *newWindow=new MainWindow;
            newWindow->show();
            newWindow->loadFile(fileName);
        }
    }
}
void MainWindow::loadFile(QString filename)
{
    printf("file name:%s\n",filename.data());
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QTextStream textStream(&file);
        while(!textStream.atEnd())
        {
            text->append(textStream.readLine());
            printf("read line\n");

        }
    }

}

MainWindow::~MainWindow()
{

}

QFile作为一个i/o设备提供将数据写入到文件或从文件读出,可以操作文本文件、二进制文件、资源文件,可以使用QTextStream或QDataStream操作,也可以使用自己操作文件。
文件名一般通过构造函数传递给文件对象:

QFile file(&filename);

也可以通过使用setFileName()函数:

QFile filefile.setFileName("file.txt");

QFile使用”/”分割目录。
使用exit()函数判读文件是否存在,使用remove()函数移动文件。
使用open()函数打开文件,close()函数关闭文件,flush()函数将缓冲区的数据刷新到文件中。数据一般通过QTextStream或QDataStream从文件读取或输入到文件,也可以使用从QIODevice继承的read(),readLine(),readAll(),write()。QFile类同时也继承了getChar(),putChar()和ungetChar()函数可以操作字符。
可以使用size()函数返回文件的大小,使用pos()函数返回当前文件的位置,或使用seek()函数进入一个新的文件目录,原型为:

bool QFileDevice::seek(qint64 pos)//将当前位置设置为pos

如果读到文件结尾,使用atEnd()将返回true

QIODevice

QIODevice是Qt所有I/O设备的基类,提供了对数据块读和写的的抽象实现,不能被实例化。从QIODevice继承的类有QFile,QBuffer,QTcpSocket。
QIODevice在打开i/o设备时必须提供打开方式作为open()函数的参数,例如本例中的QIODevice::ReadOnly|QIODevice::Text;
QIODevice::Text转换文件结尾标志,windows文件使用\r\n结尾,linux文件使用\n结尾。
然后可以使用write()或putChar()函数写入到设备中:

qint64 QIODevice::write(const char* data,qint64 maxSize)//函数返回实际写入的字节数,如果出错返回-1。
bool QIODevice::putChar(char c)
将字符写入到设备中,写入成功返回true,否则返回false

从设备读出字符通过使用read(),readLine(),readAll().

qint64 QIODevice::read(char *data,qint64 maxSize)//成功返回读出的字节数,否则返回-1
qint64 QIODevice::readLine(char* data,qint64 maxSize)//函数从设备读一行ascii字符,一直到maxSize-1,将读出的字节存储在data中,函数当读到‘\n’或maxSize-1或文件结尾。
QByteArray QIODevice::readAll()//从设备中读出剩余的所有数据,函数返回由剩余字节组成的字符数组。

QTextStream

QTextStream可以操作QIODevice,QByteArray或QString
QTextStream可以对text进行读和写,类似于c++ostream类的cout

QFile file"write.txt");
if(file.open(QFile::WriteOnly|QFile::Truncate))
{
QTextStream out(&file);
out<<"abcd";

也可以使用QTextStream在标准控制台进行输入输出

QTextStream stream(stdin);
QString line;
while(stream.readLineInto(&line))
{
..
}

**Besides using QTextStream's constructors, you can also set the device or string QTextStream operates on by calling setDevice() or setString(). You can seek to a position by calling seek(), and atEnd() will return true when there is no data left to be read. If you call flush(), QTextStream will empty all data from its write buffer into the device and call flush() on the device.**

void QTextStream::setDevice(QIODevice *device)
Note: This function resets locale to the default locale (‘C’) and codec to the default codec,
void QTextStream::setString(QString *string,QIODevice::OpenMode openMode=QIODevice::ReadWrite)
Sets the current string to string, using the given openMode. If a device has already been assigned, QTextStream will call flush() before replacing it.

Internally, QTextStream uses a Unicode based buffer
可以使用setCodec()函数改变编码



在这个例子中使用QTextEdit::append()函数将数据添加到textedit中,append函数原型为:

void QTextEdit::append(const QString& text)

QString QTextStream::readLine(qint64 maxlen=0)
从流中读出一行,将读出的数据作为QString返回



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值