Qt:Qfile与QTextStream读写文本文件 + Qt QFile /readLine()(*****)

118 篇文章 11 订阅
文章介绍了如何使用Qt的QFile和QTextStream类进行文本文件的读写操作,包括按行读取和写入,以及C++中处理文件的几种方法。QFile的readLine()函数用于按行读取数据,而QTextStream则提供了一种更方便的逐行读写方式。此外,还提到了不同平台下的文件操作差异和权限处理。
摘要由CSDN通过智能技术生成

目录

Qt:Qfile与QTextStream读写文本文件(*****)

Qt QFile按行读写数据 (*****)

[C++]Qt文本操作(按行读写)(***)

lines.push_back(line);   //将每一行依次存入到vector中

官方手册:readLine()

----------------------------------

参考:

Qt:Qfile与QTextStream读写文本文件 + Qt QFile /readLine()(****)

Qt:Qfile与QTextStream读写文本文件 + Qt QFile /readLine()(****)_ken2232的博客-CSDN博客

C++操作文件行(读取,删除,修改指定行) (****)

C++操作文件行(读取,删除,修改指定行) (****)_ken2232的博客-CSDN博客

Qt 之QDir文件目录拷贝、创建、删除 (***)

Qt 之QDir文件目录拷贝、创建、删除 (***)_ken2232的博客-CSDN博客

Qt之Qfile读取文件操作:类介绍

Qt之Qfile读取文件操作:类介绍_qfile读取文件的任意位置_ken2232的博客-CSDN博客

C++ 读取文件最后一行产生的问题

C++ 读取文件最后一行产生的问题_ken2232的博客-CSDN博客

==================

命名空间:

功能相似的局部函数:read() /write() 函数的名字相同,功能相同;但是,实际上,它们都是局部函数,也就是在不同的类中的具体实现,一般都是不一样的。

人也类似:都叫张三,这个城市的张三,和那个城市的张三,它们的身体构造,基本上都具备雄性人类的大部分、甚至是绝大部分的主要特征,但是,它们根本上就不是同一个人。

如果采用身份证号码来取代人名的话:这个号码的人就几乎完全不同于那个号码的人了。没有绝对,由于种种原因,可能同一个人同时有几个号码,或者同一个号码却同时表示几个不同的人。

问题:

1. 假如使用身份证号码来取代人名的话:没有效率,点100个人名,可能需要半天时间了。

2. 类似的100个事件,就要使用类似的100个相近的不同标记,太难记忆了。

3. 局部作用域,只要这个城市张三的老婆,不会搞混淆哪个张三是自己老公,就OK 了。

有心想用一个 write()函数就能够适用于所有的 write场景,甚至是一切场景;有心想用一种药就能包治百病;可惜,人类永远也做不到啊?

================================

Qt QFile按行读写数据  (*****)

1. 包含的头文件

#include <QDebug>
#include <QFile>

2. 读数据

QFile file("inputFile.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
     while (!file.atEnd())
     {
       QByteArray line = file.readLine();
     }
       file.close();
}

3. 写数据

QFile file("outputFile.txt");
if (file.open(QIODevice::ReadWrite | QIODevice::Text))
{
   file.write(str);
   file.flush();
   file.close();
}

[C++]Qt文本操作(按行读写)(***)

  https://www.cnblogs.com/FKdelphi/p/10310435.html

#include <QDebug>
#include <QFile>

void ReadLine()
{

    QFile file("要读的文件路径");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        while (!file.atEnd())
        {
            QByteArray line = file.readLine();
            QString str(line);
            qDebug() << str;
            displayString << str;
        }
        file.close();

    }
}

         

void WriteLine()
{

    QFile file("要写的文件路径");
    if (file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        QTextStream stream(&file);
        stream.seek(file.size());
        for (auto& i : displayString)
        {
            QString qs;
            qs.append("Content:");
            qs.append(i);
            qs.remove("\n");
            stream << qs << "\n";
        }
        file.close();
    }
}

QString转换为QByteArray

    QByteArray byte;
    QString string;
    byte = string.toAscii();

    byte = string.toUtf8();

 
QByteArray 转换为 QString

    QByteArray byte;
    QString string;
    string = QString(byte);

    string.prepend(byte);

=============

Qt:Qfile与QTextStream读写文本文件(*****)

  https://blog.csdn.net/qq_44894692/article/details/106650975

之前总结了几种用C++读写文本文件的方法,这几天用Qt时大概学了一下用Qt中的Qfile和QTextStream读写文本文件,在此做个记录。
之前对C++读写文本文件的几种方法比较:https://blog.csdn.net/qq_44894692/article/details/103618356

Qfile读文本文件:

void readwrite::readfile()
{
    QString path = QFileDialog::getOpenFileName(this, "open", "../", "txt(*.txt)");//读取文件路径
    if (!path.isEmpty())
    {
        QFile file(path);
        bool isok = file.open(QIODevice::ReadOnly);//打开方式为只读
        if (isok)
        {
            QByteArray array = file.readAll();//读取文本中全部文件
            ui.textBrowser->setText(QString(array));
        }
        file.close();//关闭文件
    }
}

Qfile写出文本文件:

void readwrite::writefile()
{
    QString path = QFileDialog::getSaveFileName(this, "save", "../", "txt(*.txt)");//写出文件的路径
    if (!path.isEmpty())
    {
        QFile file(path);
        bool isok = file.open(QIODevice::WriteOnly);//打开方式为只写
        if (isok)
        {
            QString str = ui.textBrowser->toPlainText(); //获取文本框中的内容
            file.write(str.toUtf8()); //
        }
        file.close();
    }
    
}

QTextStream读取文本文件:

void readwrite::readfile()
{
    QString path = QFileDialog::getOpenFileName(this, "open", "../", "txt(*.txt)");
    if (!path.isEmpty())
    {
        QFile file(path);
        bool isok = file.open(QIODevice::ReadOnly);
        if (isok)
        {
            QTextStream filestream(&file); //QTextStream 与file关联
            QString str;
            filestream.setCodec("UTF-8");
            while (filestream.atEnd()==false)
            {
                str.append(filestream.readLine());//逐行读取
                str.append("\n");
                //str = filestream.readAll();//一次性读取全部文件
            }
            ui.textBrowser->setText(str);
        }
        file.close();
    }
}

QTextStream写出文本文件:

void readwrite::writefile()
{
    QString path = QFileDialog::getSaveFileName(this, "save", "../", "txt(*.txt)");
    if (!path.isEmpty())
    {
        QFile file(path);
        bool isok = file.open(QIODevice::WriteOnly);
        if (isok)
        {
            QTextStream filestream(&file); //QTextStream 与file关联
            QString str = ui.textBrowser->toPlainText();
            filestream << str;//写出文件
            qDebug() << str;
        }
        file.close();
    }
    
}

使用Qt读写文本文件通常使用Qfile与QTextStream 结合,因为QTextStream 可以逐行读取,对于处理数据要相对方便一些,而且Qt提供了较多的函数接口,较C++要更快速便捷。

————————————————
版权声明:本文为CSDN博主「BetterQ.」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_44894692/article/details/106650975

C++读取文本文件的几种方法

前几天要用到C++读取文本文件,就学习了一下几种不同的读取方法:

文本文件内容如下:

第一种:直接读取,以空格换行

int main()
{
    ifstream infile;
    infile.open("qqzl.txt", ios::in);
    if (!infile.is_open())
    {
        cout << "读取文件失败" << endl;
        return;
    }
    //第一种读取方法,
    char buf[1024] = { 0 };
    while (infile>>buf)
    {
        cout << buf << endl;//输出读取的文本文件数据
    }
}

第二种:数组方法,逐行读取,可读取空格

    int main()
    {
    ifstream infile;
    infile.open("qqzl.txt", ios::in);
    if (!infile.is_open())
    {
        cout << "读取文件失败" << endl;
        return;
    }
    //第二种读取方法
    char buf[1024];
    while (infile.getline(buf,sizeof(buf)))
    {
        cout << buf << endl;
    }
    }

第三种:字符串读取,逐行读取,可读取空格

int main()

{

    ifstream infile;

    infile.open("qqzl.txt", ios::in);

    if (!infile.is_open())

    {

        cout << "读取文件失败" << endl;

        return;

    }

    //第三种读取方法

    string buf;

    while (getline(infile,buf))

    {

        cout << buf << endl;

    }

}

第四种:逐字符读取,可读取空格,但是效率较低

int main()
{
    ifstream infile;
    infile.open("qqzl.txt", ios::in);
    if (!infile.is_open())
    {
        cout << "读取文件失败" << endl;
        return;
    }
    //第四种读取方法
    char c;
    while ((c=infile.get())!=EOF)
    {
        cout << c;
    }
}

第五种:读取至Vector容器中

int main()
{
    ifstream infile;
    infile.open("qqzl.txt", ios::in);
    if (!infile.is_open())
    {
        cout << "读取文件失败" << endl;
        return;
    }
    //第五种读取方法
    string s;
    vector<string>v1;
    while (getline(infile,s))
    {
        infile >> s;
        v1.push_back(s);
    }
    for (int i = 0; i < v1.size(); i++)
    {
        cout << v1.at(i);
        cout << endl;
    }
    infile.close();
}

这是暂时总结的几种方法,就当记录一下。
————————————————
版权声明:本文为CSDN博主「BetterQ.」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_44894692/article/details/103618356

====================================

官方手册:readLine()

qint64 QIODevice::readLine(char *data, qint64 maxSize)

This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. If a line could not be read but no error ocurred, this function returns 0. If an error occurs, this function returns the length of what could be read, or -1 if nothing was read.

A terminating '\0' byte is always appended to data, so maxSize must be larger than 1.

Data is read until either of the following conditions are met:

The first '\n' character is read.maxSize - 1 bytes are read.The end of the device data is detected.

For example, the following code reads a line of characters from a file:

QFile file("box.txt");

if (file.open(QFile::ReadOnly))

{
    char buf[1024];
    qint64 lineLength = file.readLine(buf, sizeof(buf));
    
    if (lineLength != -1) {
        // the line is available in buf
    }
}

The newline character ('\n') is included in the buffer. If a newline is not encountered before maxSize - 1 bytes are read, a newline will not be inserted into the buffer. On windows newline characters are replaced with '\n'.

This function calls readLineData(), which is implemented using repeated calls to getChar(). You can provide a more efficient implementation by reimplementing readLineData() in your own subclass.

See also getChar(), read(), and write().

QByteArray QIODevice::readLine(qint64 maxSize = 0)

This is an overloaded function.

Reads a line from the device, but no more than maxSize characters, and returns the result as a byte array.

This function has no way of reporting errors; returning an empty QByteArray can mean either that no data was currently available for reading, or that an error occurred.

[virtual protected] qint64 QIODevice::readLineData(char *data, qint64 maxSize)

Reads up to maxSize characters into data and returns the number of characters read.

This function is called by readLine(), and provides its base implementation, using getChar(). Buffered devices can improve the performance of readLine() by reimplementing this function.

readLine() appends a '\0' byte to data; readLineData() does not need to do this.

If you reimplement this function, be careful to return the correct value: it should return the number of bytes read in this line, including the terminating newline, or 0 if there is no line to be read at this point. If an error occurs, it should return -1 if and only if no bytes were read. Reading past EOF is considered an error.

QString QTextStream::readLine(qint64 maxlen = 0)

Reads one line of text from the stream, and returns it as a QString. The maximum allowed line length is set to maxlen. If the stream contains lines longer than this, then the lines will be split after maxlen characters and returned in parts.

If maxlen is 0, the lines can be of any length.

The returned line has no trailing end-of-line characters ("\n" or "\r\n"), so calling QString::trimmed() can be unnecessary.

If the stream has read to the end of the file, readLine() will return a null QString. For strings, or for devices that support it, you can explicitly test for the end of the stream using atEnd().

See also readAll() and QIODevice::readLine().

-------------------------------------

QFile Class

The QFile class provides an interface for reading from and writing to files. More...

Header:

#include <QFile>

qmake:

QT += core

Inherits:

QFileDevice

Inherited By:

QTemporaryFile

Note: All functions in this class are reentrant.

Public Types

typedef

DecoderFn

Public Functions

QFile(const QString &name, QObject *parent)

QFile(QObject *parent)

QFile(const QString &name)

QFile()

virtual

~QFile()

bool

copy(const QString &newName)

bool

exists() const

bool

link(const QString &linkName)

bool

open(FILE *fh, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle)

bool

open(int fd, QIODevice::OpenMode mode, QFileDevice::FileHandleFlags handleFlags = DontCloseHandle)

bool

remove()

bool

rename(const QString &newName)

void

setFileName(const QString &name)

QString

symLinkTarget() const

Reimplemented Public Functions

virtual QString

fileName() const override

virtual bool

open(QIODevice::OpenMode mode) override

virtual QFileDevice::Permissions

permissions() const override

virtual bool

resize(qint64 sz) override

virtual bool

setPermissions(QFileDevice::Permissions permissions) override

virtual qint64

size() const override

Static Public Members

bool

copy(const QString &fileName, const QString &newName)

QString

decodeName(const QByteArray &localFileName)

QString

decodeName(const char *localFileName)

QByteArray

encodeName(const QString &fileName)

bool

exists(const QString &fileName)

bool

link(const QString &fileName, const QString &linkName)

QFileDevice::Permissions

permissions(const QString &fileName)

bool

remove(const QString &fileName)

bool

rename(const QString &oldName, const QString &newName)

bool

resize(const QString &fileName, qint64 sz)

bool

setPermissions(const QString &fileName, QFileDevice::Permissions permissions)

QString

symLinkTarget(const QString &fileName)

Detailed Description

QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.

The file name is usually passed in the constructor, but it can be set at any time using setFileName(). QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.

You can check for a file's existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)

The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.

The size of the file is returned by size(). You can get the current file position using pos(), or move to a new file position using seek(). If you've reached the end of the file, atEnd() returns true.

Reading Files Directly

The following example reads a text file line by line:

      QFile file("in.txt");

      if (!file.open(QIODevice::ReadOnly | QIODevice::Text))

          return;


      while (!file.atEnd()) {

          QByteArray line = file.readLine();

          process_line(line);

      }

The QIODevice::Text flag passed to open() tells Qt to convert Windows-style line terminators ("\r\n") into C++-style terminators ("\n"). By default, QFile assumes binary, i.e. it doesn't perform any conversion on the bytes stored in the file.

Using Streams to Read Files

The next example uses QTextStream to read a text file line by line:

      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);

      }

QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system's local 8-bit encoding is used (e.g., UTF-8 on most unix based operating systems; see QTextCodec::codecForLocale() for details). This can be changed using QTextStream::setCodec().

To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right:

      QFile file("out.txt");

      if (!file.open(QIODevice::WriteOnly | QIODevice::Text))

          return;


      QTextStream out(&file);

      out << "The magic number is: " << 49 << "\n";

QDataStream is similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.

When you use QFile, QFileInfo, and QDir to access the file system with Qt, you can use Unicode file names. On Unix, these file names are converted to an 8-bit encoding. If you want to use standard C++ APIs (<cstdio> or <iostream>) or platform-specific APIs to access files instead of QFile, you can use the encodeName() and decodeName() functions to convert between Unicode file names and 8-bit file names.

On Unix, there are some special system files (e.g. in /proc) for which size() will always return 0, yet you may still be able to read more data from such a file; the data is generated in direct response to you calling read(). In this case, however, you cannot use atEnd() to determine if there is more data to read (since atEnd() will return true for a file that claims to have size 0). Instead, you should either call readAll(), or call read() or readLine() repeatedly until no more data can be read. The next example uses QTextStream to read /proc/modules line by line:

      QFile file("/proc/modules");

      if (!file.open(QIODevice::ReadOnly | QIODevice::Text))

          return;


      QTextStream in(&file);

      QString line = in.readLine();

      while (!line.isNull()) {

          process_line(line);

          line = in.readLine();

      }

 

Signals

Unlike other QIODevice implementations, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This implementation detail means that QFile is not suitable for reading and writing certain types of files, such as device files on Unix platforms.

Platform Specific Issues

File permissions are handled differently on Unix-like systems and Windows. In a non writable directory on Unix-like systems, files cannot be created. This is not always the case on Windows, where, for instance, the 'My Documents' directory usually is not writable, but it is still possible to create files in it.

Qt's understanding of file permissions is limited, which affects especially the QFile::setPermissions() function. On Windows, Qt will set only the legacy read-only flag, and that only when none of the Write* flags are passed. Qt does not manipulate access control lists (ACLs), which makes this function mostly useless for NTFS volumes. It may still be of use for USB sticks that use VFAT file systems. POSIX ACLs are not manipulated, either.

See also QTextStream, QDataStream, QFileInfo, QDir, and The Qt Resource System.

-------------------------

QFile Class

The QFile class provides an interface for reading from and writing to files. More...

Header:
#include <QFile>
qmake:
QT += core
Inherits:
QFileDevice
Inherited By:
QTemporaryFile

qint64 QIODevice::write(const char *data, qint64 maxSize)

Writes at most maxSize bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

See also read() and writeData().

qint64 QIODevice::write(const char *data)

This is an overloaded function.

Writes data from a zero-terminated string of 8-bit characters to the device. Returns the number of bytes that were actually written, or -1 if an error occurred. This is equivalent to

  ...

  QIODevice::write(data, qstrlen(data));

  ...

This function was introduced in Qt 4.5.

See also read() and writeData().

qint64 QIODevice::write(const QByteArray &byteArray)

This is an overloaded function.

Writes the content of byteArray to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

See also read() and writeData().

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值