Thread: Fixed Length Binary I/O

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    8

    Fixed Length Binary I/O

    I have 2 integer in my structure
    Code:
    struct{
       int a;
       int b;
    }
    i hv to write a fixed length binary format in a text file. but what i dont understand is how to do this particular problem. For example, if the value of a is equal to 48, it must be stored as 48 (in decimal)
    or 30 (in hexadecimal; in C: 0x30). It must not be stored as the string “48”,
    occupying two bytes.

    thanks

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    ...binary format in a text file...
    These two things are typically mutually exclusive.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    use fopen with "wb" mode to open file as binary
    and fwrite to write a struct as binary
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    But, given that structure, if you're expecting say 00 48 to appear in the file as two bytes, then you need to do something yourself.

    Writing the whole structure in one step, whilst possible, it not portable. There are padding, alignment and endian issues which may get in the way of the result you expect.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary Tree and File I/O
    By Matus in forum C Programming
    Replies: 24
    Last Post: 12-05-2008, 12:41 PM
  2. Need help with a snake game (ncurses)
    By Adam4444 in forum C Programming
    Replies: 11
    Last Post: 01-17-2007, 03:41 PM
  3. File I/O Binary Question...
    By C+noob in forum C++ Programming
    Replies: 11
    Last Post: 07-11-2005, 07:51 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Linking error
    By DockyD in forum C++ Programming
    Replies: 10
    Last Post: 01-20-2003, 05:27 AM