seekp and binary files

This is a discussion on seekp and binary files within the C++ Programming forums, part of the General Programming Boards category; I am writing a programme which creates a binary file, but because the programme is generating bits of information which ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    10

    seekp and binary files

    I am writing a programme which creates a binary file, but because the programme is generating bits of information which need to go in different sections of the file I am trying to use seekp to jump around in the output file to the correct location.

    This is producing very unpredictable results and I wonder if it is because the length of the file has not been defined, and you can't use seekp to jump ahead of where the last byte was written.

    If this is so, is there a way of specifying the length of the file when you create it, so that you can use seekp to move around in it?

    Grateful for any advice.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Well, if you are creating a new file and want it to be a certain size, I would fill it with a value (such as 0) up to the size you want. You can use the fill_n function in the <algorithm> header to do that:

    Code:
    #include <fstream>
    #include <algorithm>
    #include <iterator>
    
    int main()
    {
        std::ofstream output("output.txt",std::ios::binary|std::ios::out);
    
        // Create a 500 byte file stuffed with 0's
        std::fill_n(std::ostream_iterator<char>(output),500,0);
    
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bits in files
    By robquigley in forum C++ Programming
    Replies: 1
    Last Post: 10-06-2003, 12:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21