Reputation: 4098
I am using QFile
and QTextStream
to first read a file and then write the read contents unmodified back into the same file. Here is the code:
QFile inFile("file.txt");
if(!inFile.open(QFile::ReadOnly | QFile::Text))
{
qCritical() << "ERROR: Unable to open input file: " << "file.txt";
exit(1);
}
QTextStream inStream(&inFile);
QString fileContents = inStream.readAll();
inFile.close();
QFile outFile("file.txt");
if(!outFile.open(QFile::WriteOnly | QFile::Text))
{
qCritical() << "ERROR: Unable to open output file: " << "file.txt";
exit(1);
}
QTextStream outSream(&outFile);
outSream << fileContents;
outFile.close();
However, this transforms the file.txt given below:
1
2
3
4
5
into
12345
i.e. newlines are getting removed in this process. Why is this happening? How can I prevent it?
Upvotes: 1
Views: 3033
Reputation: 37
The solution is to not use QFile::Text or QIODevice::Text, if you are reading, just use QIODevice::ReadOnly , in that way you can also figure out the exact line ending used and handle them appropriately. I had this problem with Mac(CR) or '\r' line ending while opening with QIODevice::Text.
Upvotes: 1
Reputation: 2771
About QIODevice::Text
in openMode the official document says.
When reading, the end-of-line terminators are translated to '\n'. When writing, the end-of-line terminators are translated to the local encoding, for example '\r\n' for Win32.
It says Win32,while working on Win64,Qt5.8 I found it works differently.
With QIODevice::Text
in openMode, QIODevice::readAll()
remove all '\r','\t'
.
And talk about \n
,they are replaced by \r
whatever openMode is using.
May be removed if using QIODevice::Text
mode.
Upvotes: 1
Reputation: 6329
The QIODevice::Text
flag passed to open()
tells Qt
to convert Windows-style line terminators (\r\n
) into C++-style terminators (\n
).
Are you operating in Windows? You should be able to see the \r\n
in a binary editor on the input and the output file.
Upvotes: 2