Weird behavior: fputc adds an extra character.

S

Shafik

Hello folks,

I am having a really weird problem. Under windows XP, a simple C
program designed to write to a file has been adding EXTRA characters
to the output file.

First I used "fwrite", to write, lets say, 1000 bytes in binary. The
output contained 1022 bytes, even though fwrite told me (returned)
that it only wrote 1000 bytes.

After much debugging, I saw that every time there was a "0x0A" byte to
be written, a "0x0D" was automatically appended! Thus adding extra
bytes to the file. What is going on?

I tried a simple loop with fputc instead of fwrite, and the behavior
was the exact same.


Anyone experienced this sort of thing before?

Thanks,
--Shafik
 
G

Guest

Shafik said:
Hello folks,

I am having a really weird problem. Under windows XP, a simple C
program designed to write to a file has been adding EXTRA characters
to the output file.

First I used "fwrite", to write, lets say, 1000 bytes in binary. The
output contained 1022 bytes, even though fwrite told me (returned)
that it only wrote 1000 bytes.

After much debugging, I saw that every time there was a "0x0A" byte to
be written, a "0x0D" was automatically appended! Thus adding extra
bytes to the file. What is going on?

'\n' is guaranteed to be a single character in standard C, but it is
not a single character in your operating system's text format, so
fputc e.a. need to translate it at runtime. To disable this, don't
open the file in text mode, open the file in binary mode using the
second argument of fopen(). See also <http://c-faq.com/stdio/
fopenbinary.html>.
 
S

Shafik

'\n' is guaranteed to be a single character in standard C, but it is
not a single character in your operating system's text format, so
fputc e.a. need to translate it at runtime. To disable this, don't
open the file in text mode, open the file in binary mode using the
second argument of fopen(). See also <http://c-faq.com/stdio/
fopenbinary.html>.

Perfect, thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top