I met a weird thing when using fwrite() and fputc()  
Author Message
Vivienne.Zhou





PostPosted: Visual C++ General, I met a weird thing when using fwrite() and fputc() Top

I am using VS 2005.

In a project when I was trying to write some unsigned char into a file, I used fwrite() and fputc(). But I found whenever I tried to write 0x0a, fwrite() function automaticly wrote 0x0d before 0x0a. So I wrote a small test to test it. Here is it:

FILE* file;

unsigned char p = 0x0a;

long offset = ftell(file); // here the offset = 0;

fwrite(*p,1,1,file);

offset = ftell(file); // after this, the offset = 2. and in the file I

// found 0x0d and 0x0a was written.

I can't understand. I just want to write byte by byte, automatically inserted byte 0x0d will cause problems in my project.

can someone tell me what is the cause and how to avoid the unwanted byte



Visual C++9  
 
 
Mike Danes





PostPosted: Visual C++ General, I met a weird thing when using fwrite() and fputc() Top

Most probably you have opened the file in text mode. In text mode the CRT functions automatically add 0x0d to create the Windows style newline terminator (CR LF). You need to open the file in binary mode:

FILE *file = fopen("d:\\foo.bin", "wb"); // note the b character from the mode string


 
 
Sarath.





PostPosted: Visual C++ General, I met a weird thing when using fwrite() and fputc() Top

Is this your production code
It seems that you've a catch in what you requested to write.

unsigned char p = 0x0a;

long offset = ftell(file); // here the offset = 0;

fwrite(*p,1,1,file);

I doubt, whether this code will compile or not.
you are passing *p as the data to write. You need to pass &p for writing the same, since fwrite accepts a void* pointer.



 
 
Vivienne.Zhou





PostPosted: Visual C++ General, I met a weird thing when using fwrite() and fputc() Top

Yes you are right! I mistyped, it should be &p, instead of *p

however I have got the answer, thank you very much.


 
 
Sentius





PostPosted: Visual C++ General, I met a weird thing when using fwrite() and fputc() Top

I have same problem, what was your solution