Thread: write function writing more than one byte

  1. #1
    Registered User
    Join Date
    Nov 2004

    write function writing more than one byte

    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.

    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. I have been strugling with this for a while, and I can't seem to solve it. I think I need someone else to look over my code. Thanks.

  2. #2
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Are you opening the file in text mode or binary mode? If you opened it in text mode, then '\n' characters when written to a file will automatically be replaced with "\n\r" on a Windows system.

    One quick check you can do is, at the breakpoint check the value of ch, and then check what are the 2 characters that were written to the file. If the file was opened in text mode, ch is '\n' and the file contains '\r\n' at the end, then chances are that's the problem. It's a general sort of debugging strategy that you can use in all cases: Search for a pattern, and find out what might cause that particular pattern to occur.

    Yeah, and what anonytmouse is about to say in the next post .
    Last edited by Hunter2; 11-15-2004 at 12:40 PM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  3. #3
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    [edit]Hunter's suggestion is more promising.[/edit]

    I don't think (tentative) you can mix C++ iostream based I/O with C file functions and get reliable results. Try using iostream::tellp instead. If you are still having troubles, consider posting your actual code instead of pseudo code.
    Last edited by anonytmouse; 11-15-2004 at 12:40 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. help w/ write() function and open() function
    By Landroid in forum C Programming
    Replies: 1
    Last Post: 04-10-2005, 11:38 AM
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM