Howto Print

Thread: Howto Print \0 to a File

to a File

This is a discussion on Howto Print

Thread: Howto Print \0 to a File

to a File
within the C++ Programming forums, part of the General Programming Boards category; I have a requirement to pad out some data in a binary file with the null charactor '

Thread: Howto Print \0 to a File

' added every ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    19

    Howto Print \0 to a File

    I have a requirement to pad out some data in a binary file with the null charactor '\0' added every second or thrid charactor. Try as I may I cannot prevent the app from ignoring the null charactor.

    I have tryed various castings and conversions without any luck.

    pseudo code below shows what I have right now.

    Code:
    string data = "J\0O\0H\0N\0";
    ofstream File;
    
    file.open("c:\\somefile.dat", ios_base::binary | ios_base::in | ios_base::out);
    
    file.write(data.c_str, sizeof data)

    Only the first char 'J' makes it to the file followed by some junk equal to the sizeof data - the first char.



    Many Thanks...

    JohnD..

  2. #2
    Registered User
    Join Date
    Jun 2003
    Posts
    245
    "put" will do what you want. However, as long as you give "write" the correct size, it should work also. Ie. Don't use "sizeof"
    Last edited by _Elixia_; 12-15-2003 at 06:35 PM.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    19
    Boy that was a quick reply!

    I have not tryed put yet but write does not work and I can see it writes J@somejunk to the destination file with a hex editor.

    J..

  4. #4
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    The constructor has no way of knowing that the string is longer than the first binary 0 unless you tell it.

    Code:
    string data("J\0O\0H\0N\0",8);
    ofstream File;
    file.open("c:\\somefile.dat", ios_base::binary | ios_base::in | ios_base:out);
    file << data;
    //or
    file.write(data.data(),data.size());

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 01:44 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-22-2008, 12:19 AM
  3. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 02:19 PM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 04:30 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 05:10 PM