Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c++ - Why does ofstream insert a 0x0D byte before 0x0A?

I'm outputing an array of unsigned characters in C++ using ofstream fout("filename"); but it produces a spurious character in between. This is the part of the code that makes the problem:

for(int i = 0; i < 12; i++)
fout << DChuffTable[i];

and this is the definition of the array:

unsigned char DChuffTable[12] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B};

In the output file I get a spurious 0x0D between 0x09 and 0x0A. I checked the array in debugging mode right before it's going to get printed and it's not changed. Please tell me what you think of this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your stream is opening in text mode, and since 0x0A is the line feed (LF) character, that's being converted by your stream to 0x0D 0x0A, i.e. CR/LF.

Open your stream in binary mode:

std::ofstream fout("filename", std::ios_base::out | std::ios_base::binary);

Then line ending conversions should not be performed.

This is usually considered a good idea anyway, as streams can go bizarre w.r.t. flushing when in text mode.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...