Qt: Qfile and QTextStream read and write text files + Qt QFile /readLine() (*****)

Table of contents

Qt: Qfile and QTextStream read and write text files (*****)

Qt QFile reads and writes data by row (*****)

[C + +] Qt text operation (read and write by line) (***)

lines.push_back(line); //store each line in the vector in turn

Official manual: readLine()

———————————-

Reference:

Qt: Qfile and QTextStream read and write text files + Qt QFile /readLine() (****)

Qt: Qfile and QTextStream read and write text files + Qt QFile /readLine() (****)_ken2232’s blog – CSDN blog

C ++ operate file line (read, delete, modify specified line) (****)

C + + operation file line (read, delete, modify the specified line) (****)_ken2232’s blog – CSDN blog

Qt’s QDir file directory copy, create, delete (***)

Qt’s QDir file directory copy, create, delete (***) – ken2232’s blog – CSDN blog

Qt’s Qfile read file operation: class introduction

Qt’s Qfile read file operation: class introduction_qfile reads any position of the file_ken2232’s blog-CSDN blog

C++ reads the problem of the last line of the file

C ++ reads the problem of the last line of the file – ken2232’s blog – CSDN blog

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

Namespaces:

Local functions with similar functions: The read() /write() functions have the same name and the same function; however, in fact, they are all local functions, that is, specific implementations in different classes, Usually it’s different.

People are also similar: are called Zhang San, Zhang San in this city, and Zhang San in that city, their body structure basically has most of the male human beings, even most of them The main characters, however, are not fundamentally the same person.

If an ID number is used instead of a person’s name: the person with this number is almost completely different from the person with that number. There is no absolute. Due to various reasons, the same person may have several numbers at the same time, or the same number may represent several different people at the same time.

question:

1. If you use the ID card number to replace the name: it is not efficient, and it may take half a day to count 100 names.

2. For 100 similar events, you need to use 100 similar different tags, which is too difficult to remember.

3. Local scope, as long as Zhang San’s wife in this city does not confuse which Zhang San is her husband, it is OK.

I want to use one write() function to be applicable to all write scenarios, or even all scenarios; I want to use one medicine to cure all diseases; unfortunately, human beings will never be able to do it?

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

Qt QFile read and write data by row (*****)

1. Included header files

#include <QDebug>
#include <QFile>

2. Read data

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

3. Write data

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

[C++]Qt text operation (read and write by line)(***)

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

#include
#include

void ReadLine()
{

QFile file(“The file path to read”);
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(“The file path to write”);
if (file.open(QIODevice::ReadWrite | QIODevice::Text))
{
QTextStream stream( & amp; file);
stream. seek(file. size());
for (auto & amp; i : displayString)
{
QString qs;
qs.append(“Content:”);
qs.append(i);
qs.remove(“\
“);

stream << qs << "\ ";
}
file. close();
}
}

QString to QByteArray

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

byte = string.toUtf8();

QByteArray to QString

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

string.prepend(byte);

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

Qt: Qfile and QTextStream read and write text files (*****)

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

I have summed up several methods of reading and writing text files with C ++ before. When I used Qt in the past few days, I probably learned to read and write text files with Qfile and QTextStream in Qt. I will make a record here.
Comparison of several methods of reading and writing text files in C ++ before: https://blog.csdn.net/qq_44894692/article/details/103618356

Qfile reads text files:

void readwrite::readfile()
{
QString path = QFileDialog::getOpenFileName(this, “open”, “../”, “txt(*.txt)”);//read file path
if (!path. isEmpty())
{
QFile file(path);
bool isok = file.open(QIODevice::ReadOnly);//Open mode is read-only
if (isok)
{
QByteArray array = file.readAll();//Read all files in the text
ui.textBrowser->setText(QString(array));
}
file.close();//Close the file
}
}

Qfile writes a text file:

void readwrite::writefile()
{
QString path = QFileDialog::getSaveFileName(this, “save”, “../”, “txt(*.txt)”);//write the path of the file
if (!path. isEmpty())
{
QFile file(path);
bool isok = file.open(QIODevice::WriteOnly);//Open mode is write-only
if (isok)
{
QString str = ui.textBrowser->toPlainText(); //Get the content in the text box
file.write(str.toUtf8()); //
}
file. close();
}

}

QTextStream reads text files:

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( & amp;file); //QTextStream is associated with file
QString str;
filestream.setCodec(“UTF-8”);
while (filestream. atEnd()==false)
{
str.append(filestream.readLine());//Read line by line
str.append(“\
“);
//str = filestream.readAll();//Read all files at once
}
ui.textBrowser->setText(str);
}
file. close();
}
}

QTextStream writes a text file:

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( & amp;file); //QTextStream is associated with file
QString str = ui.textBrowser->toPlainText();
filestream << str;//write the file
qDebug() << str;
}
file. close();
}

}

Using Qt to read and write text files usually uses the combination of Qfile and QTextStream, because QTextStream can be read line by line, which is relatively convenient for data processing, and Qt provides more function interfaces, which is faster and more convenient than C++.

—————
Copyright statement: This article is an original article of CSDN blogger “BetterQ.”, and follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this statement.
Original link: https://blog.csdn.net/qq_44894692/article/details/106650975

Several methods of C++ to read text files

A few days ago, I used C++ to read text files, so I learned several different reading methods:

The content of the text file is as follows:

Type 1: read directly, wrap with a space

int main()
{
ifstream infile;
infile.open(“qqzl.txt”, ios::in);
if (!infile.is_open())
{
cout << "Failed to read file" << endl;
return;
}
//The first read method,
char buf[1024] = { 0 };
while (infile>>buf)
{
cout << buf << endl;//output the read text file data
}
}

Second method: array method, read line by line, spaces can be read

int main()
{
ifstream infile;
infile.open(“qqzl.txt”, ios::in);
if (!infile.is_open())
{
cout << "Failed to read file" << endl;
return;
}
//Second read method
char buf[1024];
while (infile. getline(buf, sizeof(buf)))
{
cout << buf << endl;
}
}

Type 3: String reading, line by line, spaces can be read

int main()

{

ifstream infile;

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

if (!infile.is_open())

{

cout << "Failed to read file" << endl;

return;

}

//Third reading method

string buf;

while (getline(infile,buf))

{

cout << buf << endl;

}

}

The fourth type: read character by character, spaces can be read, but the efficiency is low

int main()
{
ifstream infile;
infile.open(“qqzl.txt”, ios::in);
if (!infile.is_open())
{
cout << "Failed to read file" << endl;
return;
}
//The fourth read method
char c;
while ((c=infile.get())!=EOF)
{
cout << c;
}
}

Fifth: Read to Vector container

int main()
{
ifstream infile;
infile.open(“qqzl.txt”, ios::in);
if (!infile.is_open())
{
cout << "Failed to read file" << endl;
return;
}
//The fifth read method
string s;
vectorv1;
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();
}

This is a few methods summarized temporarily, just record it.
—————
Copyright statement: This article is an original article of CSDN blogger “BetterQ.”, and follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this statement.
Original link: https://blog.csdn.net/qq_44894692/article/details/103618356

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

Official manual: 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 occurred, 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 ‘\
‘ 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 (‘\
‘) 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 ‘\
‘ .

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 (“\
” or “\r\
“), 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

qmake:

QT + = core

Inherits:

QFileDevice

Inherited By:

QTemporaryFile

  • List of all members, including inherited members
  • Obsolete members

Note: All functions in this class are reentrant.

Public Types

typedef

DecoderFn

Public Functions

QFile(const QString & amp;name, QObject *parent)

QFile(QObject *parent)

QFile(const QString & amp;name)

QFile()

virtual

~QFile()

bool

copy(const QString & amp; newName)

bool

exists() const

bool

link(const QString & amp; 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 & amp; newName)

void

setFileName(const QString & amp;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 & amp; fileName, const QString & amp; newName)

QString

decodeName(const QByteArray & localFileName)

QString

decodeName(const char *localFileName)

QByteArray

encodeName(const QString & fileName)

bool

exists(const QString & amp; fileName)

bool

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

QFileDevice::Permissions

permissions(const QString & amp; fileName)

bool

remove(const QString & amp; fileName)

bool

rename(const QString & amp; oldName, const QString & amp; 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\
“) into C++ -style terminators (“\
“). 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( & amp;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( & amp;file);

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

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 ( or ) 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 de vice 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
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 & amp;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().