Thread: File format

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

    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?


    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?


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    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.
    #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.

  3. #3
    Registered User
    Join Date
    Aug 2001
    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, 02:46 PM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM