I want to write data to a file one byte at a time. I am having a problem that for some reason the write function is writing 2 bytes instead of one. Here is the code. Code: int begin, end, dummy; begin = ftellp(); //get the current position bin3ds2.write ( &ch, 1 ); end = ftellp( file ); //get the current position if( end - begin != 1 ) { ++dummy //a breakpoint is here } If it works correctly end - begin should always be one, but sometimes it's two. I think that something else in my code might be causing this to happen, but I don't know what. Can anyone help me with this, or maybe I could send you my code and you could look at it for me. Thanks.
Is (end - begin) just sometimes 2 or is it always 2? What is ftellp()? I assume you mean ftell()? Shouldn't you give ftellp a parameter when you get the begin file position? How is bin3ds2 defined? Which class is it?
(end - begin) is just sometimes 2. Here is the definition of ftellp(): int ftellp( ) { return bin3ds2.tellp(); } bin3ds2 is defined as: ofstream bin3ds2;
some people suggested that I might be opening the file in text mode. I changed my open statement to the following, but it still writes 2 bytes sometimes. I changed my call to open to this: studio.bin3ds2.open( ofn.lpstrFile, ios:ut || ios::binary );
The code snippet wouldn't compile, but I assume this is just typo's in the posting? ftellp() takes no paramaters, but in the sample code is takes a parameter "file" in the second call? I would try: (a) Replace write with put, just as an experiment (b) Ensure that begin is a value you expect it to be, and ensure that it has not changed at the point of the if line I don't see any obvious case for a data corruption in the snippet. Do you have any other threads running and potentially alter the value in begin? If this is the case simply writing int dummy,begin,end; can change this case. I'm not sure off hand what your problem is, but if you could send me your code I'd take a look at it quickly for you.