PDA

View Full Version : QIODevice



reg
3rd February 2017, 10:37
Hi,
I am writing more than one line to text file with QIODevice::ReadWrite,
Although there are a lot of lines, in text file they are at the same line,
So reading it is so complex.
\n does not work,

Can anyone help plese?
For example:
My data is like :
a21
b34
apple
45r

But when I write it to text :
a21 b34 apple 45r

I want to prenevt this.

d_stranz
3rd February 2017, 23:26
Are you adding QIODevice::Text to the OpenMode? If you want newlines in the output, you have to explicitly write them if you are using QIODevice directly to write the files:



iodevice.write( mystring );
iodevice.write( "\n" );


But for text files, it is more usual to create a QTextStream and a QFile and use that combination to write and read text data:



// Writing:

QFile file("out.txt");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;

QTextStream out(&file);
out << mystring << "\n";

// Reading:
QFile file("in.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;

QTextStream in(&file);
while (!in.atEnd()) {
QString myString = in.readLine(); // readline automatically removes the EOL
// do something with "mystring"
}

Gokulnathvc
12th September 2017, 14:30
You can try with "/r/n" for Carriage Return.

d_stranz
12th September 2017, 16:24
You can try with "/r/n" for Carriage Return.

Yes, you can try. What you will get is a file that contains "/r/n" on each line. You might have better luck if you try "\r\n".

By the way, using "\n" will have exactly the same effect. On Windows, the device drivers add the "\r" automatically to give Windows-style CRLF line endings. In linux, "\n" (new line) is good enough, so that is all the drivers write.

Lesiok
12th September 2017, 16:53
Yes, you can try. What you will get is a file that contains "/r/n" on each line. You might have better luck if you try "\r\n".

By the way, using "\n" will have exactly the same effect. On Windows, the device drivers add the "\r" automatically to give Windows-style CRLF line endings. In linux, "\n" (new line) is good enough, so that is all the drivers write.Of course in TEXT mode only.