File format

This is a discussion on File format within the C++ Programming forums, part of the General Programming Boards category; Is there a way to set up a record type for a file, similiar to Cobol's set for a file ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Location
    Fort Worth, TX
    Posts
    53

    Question File format

    Is there a way to set up a record type for a file, similiar to Cobol's set for a file format?

    example

    Name Address Phone

    Is there a way to set up an object to read it all of the records from a file or do I have to read invidual pieces of the record?

    Bman1176

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,540
    No idea about cobol, but it's easy to
    [list=1][*]declare a structure to define the format/type of data you want to store.[*]define an array of that structure to store all your data[*]load/save that array in a single operation[/list=1]

    This is the 'C' answer.
    Code:
    #include <stdio.h>
    
    #define MAX_RECORDS 100
    
    struct foo {
        char    name[30];
        char    address[100];
        char    phone[20];
    };
    typedef struct foo foo_st;
    
    foo_st  records[MAX_RECORDS] = {
        { "Fred Flintstone", "Bedrock", "1234-5678" },
    };
    
    int main ( ) {
        FILE *fp = fopen( "rec.bin", "wb" );
        fwrite( records, sizeof(foo_st), MAX_RECORDS, fp );
        fclose( fp );
        return 0;
    }
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    The "C++" version would use an fstream or an ofstream to write to file and an fstream or ifstream to read from file instead of the FILE *. There are comparable stream member functions to write and read an entire struct to/from file with a single operation, although it may be restricted to use with binary files instead of text files. look up the stream member functions read() and write() in your favorite text or online manual.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

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