Al2O3
Al2O3

Reputation: 3203

How to avoid reading mistaken '\n' from file?

A bad way to store bytes:
I stored about some bytes in a file. The bytes were made up of arbitrary bits( 1 or 0).
About ten bytes form a log item. I add a '\n' at the end of the log.
Later when I read from the file(the file was stored and read both in Text format).
I found some two bytes of the log make up a '\n'(0x0d,0x0a).
But I use 'readLine()' of the stream of the file to read contents of the file, which failed to recognize the correct end of a line obviously.
What I got turned out to be a mass, but is there a better way to store the bytes(containing arbitrary 1 or 0) and read from the file?
I use c++ in qt, a solution under the IDE should be better if possible.

My English is poor. Thank for your patience to read!

Upvotes: 0

Views: 134

Answers (2)

pradipta
pradipta

Reputation: 1744

You can use a special character to in place of the '0' then store to the file and add the '\n' at the end of the line. Try this,it may help.

Upvotes: 0

AutomatedMike
AutomatedMike

Reputation: 1512

I suspect you are using windows and you're writing in text mode and reading in binary mode.

On windows text files that are saved to the filesystem should have \r\n (0x0d,0x0a) at the end of the line. Writing in text mode automatically adds the \r when ever there is a \n. Reading in text mode will remove the \r so you should never see it.

If you read and write in the same mode (text or binary) then you will see the same data as you wrote. On linux there in no difference between text mode and binary mode but you should get the mode right to keep your code portable..

If this is a binary file (sounds like you're writing bytes rather than strings) then you should probably use binary mode for both reading and writing.

Upvotes: 1

Related Questions