1 文件普通读写
略
2 流式操作
QFile file("in.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
process_line(line);
}
示例
widegt.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QFileDialog>
#include <QTextStream>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
public slots:
void showfile()
{
QString filename = QFileDialog::getOpenFileName();
le->setText(filename);
#if 0
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!file.atEnd()) {
QByteArray line = file.readLine();
// process_line(line);
te->append(line);
}
#endif
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
// process_line(line);
te->append(line);
}
}
private:
QTextEdit *te;
QLineEdit *le;
QPushButton *pb;
};
#endif // WIDGET_H
wigdet.cpp
#include "widget.h"
#include <QVBoxLayout>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
te = new QTextEdit;
te->setMinimumSize(640, 480);
le = new QLineEdit;
pb = new QPushButton("showtxt");
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(te);
vbox->addWidget(le);
vbox->addWidget(pb);
setLayout(vbox);
connect(pb, SIGNAL(clicked(bool)), this, SLOT(showfile()));
}
Widget::~Widget()
{
}
3 文件属性
QFileInfo info1("/home/bob/bin/untabify");
info1.isSymLink(); // returns true
info1.absoluteFilePath(); // returns "/home/bob/bin/untabify" info1.size(); // returns 56201
info1.symLinkTarget(); // returns "/opt/pretty++/bin/untabify"
文件夹遍历
QDir dir;
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
}
main.cpp
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDir dir;
QFileInfoList list = dir.entryInfoList();
std::cout << " Bytes Filename" << std::endl;
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
std::cout << fileInfo.size()<< "\t"<<fileInfo.fileName().toStdString().c_str();
std::cout << std::endl;
}
return a.exec();
}