Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Need help reading and writing from binary file

  1. Aug 24, 2006 #1
    I'm writing a large amount of data to a binary file. Trouble is, I don't know how much until the program finishes executing.

    Given this, I'd like to rewind back to the begining of the binary file and write an element indicating how many records I wrote to the binary file - this way I can create arrays in another program and read in the data to do some fun stuff with it.

    I've tried:
    fseek(filename, sizeof(int), SEEK_SET);
    fwrite(&data, sizeof(int), 1, filename);

    to no avail. Can someone please assist?
  2. jcsd
  3. Aug 24, 2006 #2


    User Avatar
    Homework Helper

    When reading any binary file (or even ASCII), the end of the file will be indicated with an EOF (end of file). There's no need to append the file size. For example.

    Code (Text):

    char buffer[100];
    while( !feof( stream ) )
          /* Attempt to read in 10 bytes: */
          count = fread( buffer, sizeof( char ), 100, stream );

    I'm also curious about this application. Why is it that you do not know the amount of bytes you are going to write. The write operations should be from a buffer, some sort of array whose size ( sizeof(arr) ) can be found.
  4. Aug 24, 2006 #3
    It's a program to stochastically simulate chemical reactions.

    Since it's stochastic, it is a probabilistic problem and there is no way to know beforehand how many reactions you will have in any given interval.

    Basically, each time a reaction occurs I'm writing the time at which it occurs, and the reaction number to a binary file. At the end of the simulation I'd like to output the total number of reactions to the begining of the file so I can write another section of code to parse this data - ie so I can know the state of the system at any point in time.
  5. Aug 24, 2006 #4


    User Avatar
    Homework Helper

    Unless the file you are writing is very very large, you can write all of this information into a buffer. Or of course, you can keep track of how many characters you have written internally in a variable. fwrite() returns the number of bytes it has written.

    As far as I know however, it is not possible to shift the bytes in the file. If after all my suggestions you still for some reason want to write the written number of bytes into the file "header", then reserve the first four bytes for this purpose. I'm assuming that your file would not be larger than (2^32) bytes (~4200 Gigabytes). Write junk data to it first and then append it.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook