Convert a text file to a binary file

This is a discussion on Convert a text file to a binary file within the C Programming forums, part of the General Programming Boards category; I'm trying to read one record at a time from a text file - putting the record, using strncpy, into ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    20

    Question Convert a text file to a binary file

    I'm trying to read one record at a time from a text file - putting the record, using strncpy, into a structure- then writing it to a binary file to be reused later as a binary file.

    However, I'm having trouble converting the records to binary, I thought the following would work- and I have tried many variations- but it wont.

    struct record{
    char type = {"\0"}; /*one space then null*/
    char sort[7] = {" \0"}; /*6 spaces then null*/
    char part[21] = {" \0"}; /*20 spaces then null*/
    };


    Once the record is read into the structure I then use:

    fprintf(newfile_ptr,"%c%7s%21s", etc........);

    Is there something wrong with my syntax?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    char type = {"\0"}; /*one space then null*/


    This is an incorrect assignment. You are using a string when 'type' is only a single character. Use single quotation marks:

    char type = '\0';

    Just use fwrite() and write the whole structure in one shot.

    fwrite( struct_pointer, sizeof( struct record ), 1, filePointer );

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    20
    I've already tried

    struct record{
    char type = '\0';
    char sort [7] = ' \0';
    char part [21] = ' \0';
    };

    and I get 3 errors saying 'declaration missing ;'

    I just don't know what else to try. I must be missing something.

    Also, the original file is text, so I didn't think I could use fwrite().

    help!!

    Lynds

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,687
    > struct record{
    > char type = '\0';
    > char sort [7] = ' \0';
    > char part [21] = ' \0';
    > };

    You can't declare and initialise a structure like this

    Code:
    struct record { 
        char type; 
        char sort [7]; 
        char part [21]; 
    }; 
    
    struct record foo = {
        '0',
        { 0 },
        { 0 }
    };

    Then fwrite as Quzah suggests

  5. #5
    Registered User
    Join Date
    Aug 2001
    Posts
    20
    Sorry to be a pain, but how do you reference the structure if it is one of three in a union?

    Anything like this?

    struct record1{
    char type;
    char sort [7];
    char part [21];
    };

    struct record2{
    char type;
    char sort [7];
    };

    struct record3{
    char type;
    char sort [7];
    char name [21];
    };

    union a_rec{
    struct record1 old;
    struct record2 new;
    struct record3 delete;
    };

    struct a_rec old old2 = {
    '0',
    {0}, /*Are these nulls \0 ?*/
    {0}
    };

    Same for 'new' and 'delete'?

    To put the data in the structure is it:

    a_rec_ptr->old.type = *bstring_ptr;

    /*bstring_ptr just a pointer to the file I'm reading from.*/

    I'm starting to get confused as to how to reference it because of the union.

    Lynds

  6. #6
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Hi again,

    Code:
     struct IR_Rec {
            char type;
            char cust_code[6];
            blah blah blah;
            };
     
     struct del_rec {
           your members;
           };
     
     struct  new_cust {
           your members;
           };
    
      typedef union {
          struct  IR_Rec   iss_ret;
          struct  Del_Rec  deleted;
          struct  new_cust create;
          } RECORDS;
    
       RECORDS all_recs;
    
       all_recs.iss_ret.type = getch // or fgetc(fp);
       fgets(all_recs.iss_ret.cust_code, 6, fp);
    to answer first part you will have to read the record using text file input functions - fgetc, fgets or fscanf to fill your structure members then using fwrite write to the binary out file

    fwrite(&all_recs, sizeof(RECORDS), 1, bin_fp);
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    > to answer first part you will have to read the record using text
    > file input functions - fgetc, fgets or fscanf to fill your structure
    > members then using fwrite write to the binary out file

    No. You'll use 'text input functions' if you're filling the data from the console (ie: the user is "filling" your records). However, once that is done, you just read the whole thing in one shot from the disk (same goes for writing). Use fread/fwrite for this.

    'new' and 'delete' are C++ operators and are not C.

    Keep in mind, if you're using a union, you need to make sure you're accessing its internals correctly:

    union u {
    int a;
    float b;
    char c;
    };

    union u abc;

    abc.a = 10; //access 'a'
    abc.b = 10.0; //access 'b', overwrites the data in 'a'
    abc.c = 'c'; //access 'c', overwrites the data in b

    Union's data members all exist in the same space in memory. Changing one changes them all.

    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    with respect, quzah, this is a project which is familiar to some people on here.

    No. You'll use 'text input functions' if you're filling the data from the console (ie: the user is "filling" your records). However, once that is done, you just read the whole thing in one shot from the disk (same goes for writing). Use fread/fwrite for this.

    NO NO!
    we read the first input text file from disk....
    into structures which are members of a union,
    then it is up to ourselves whether we create an output file in either binary or text.

    I was merely pointing out the options to cyber kitten for reading from the text file then writing to the binary output file if this was her preferred method.

    Secondly, I know that delete and new are C++ operators, this is why I used del_rec instead of "delete" and new_customer instead of "new".

    Thirdly, any computeach student, this should never be your first port of call to seek help for any problems you may be having. The posters on here are unfamiliar with the specific problem for which you seek an answer. Some times there solutions are like getting from glasgow to edinburgh via london. Refer to course material. This is all in there cyber, and you have done this before.
    Last edited by bigtamscot; 01-31-2002 at 02:59 AM.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  9. #9
    Registered User
    Join Date
    Aug 2001
    Posts
    20
    Bigtamscot,

    Referring to your posting on 30/1, the only problem I seem to have now is how to pass all_recs to a function. I've spent the entire morning looking throught the stage 3 folder and I can't find an example of it anywhere.

    So far I've got (using your example details):

    int validate(union RECORDS *paint_ptr, char *code_ptr, int number);


    void main()
    {

    RECORDS all_recs;

    Then I've used fgets in my program to get the record, then I want to use this info. in a function to check if the record is valid.

    I get an error when I do the following:

    status=validate(&all_recs,str,record_type);

    What syntax do I use to pass the union so that I can use it in the function 'validate'?

    I have also tried:

    RECORDS all_recs, *paint;
    all_recs_ptr=&paint;
    then pass all_recs_ptr
    but this doesn't seem to work either.

    If status is valid I then do:

    fwrite(&all_recs,sizeof(RECORDS),1,fp);

    Thanks
    Lynds

  10. #10
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Sorry it has taken me so long, but the problem may lie with you declaring another variable of the type RECORDS in your call to the function.
    Code:
    int validate(union RECORDS *paint_ptr, char *code_ptr, int number);  
    
    /*should be - RECORDS atfer the typedef can be considered a data type of its own*/
    
    int validate(RECORDS *paint_ptr, char *code_ptr, int number);
    
    /*you can then pass the arguments via the pointer*/
    
    RECORDS all_recs, 
                    *paint = &all_recs;
    
    status=validate(paint,str,record_type);
    Last edited by bigtamscot; 02-03-2002 at 09:14 AM.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  11. #11
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    OOPS, I forgot to include the ampersand before, rectified by editing incase you missed it.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  12. #12
    Registered User breed's Avatar
    Join Date
    Oct 2001
    Posts
    91
    Hi Cyber Kitten,

    reading your post & BigTamScotts, I'm not far behind you too on the course as Big Tam knows.
    Any way i try not to make my progs to complicated, and attempting to answer your Q, about passing your union to a function, i noticed that you said that you used fgets() to read the text, well whatever you used it to read into i.e. a string or a pointer then i faound that if i passed the string/pointer to the function.
    Then declared the union as norm RECORDS all_recs;
    in the funtion, then used the the member path

    all_recs.iss_ret.cust_code;

    to access or manipulate the member, this usually works.
    have you put a watch on all_recs to see if the data is being read into it?

    as for converting data from text to binary i thought that the computer did this automatically as long as you have opened a read text file & a write binary file then used fwrite() (using a pointer to the write binary) to convert the file.

    If i'm wrong please post more on this subject as it wil udoubtedly help me with my course work
    Before you judge a man, walk a mile in his
    shoes. After that, who cares.. He's a mile away and you've got
    his shoes.
    ************William Connoly

  13. #13
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Hi Breed,
    You really should have attended the prep course at dudley. Get your name down asap. this will help you no end, espeically the hand outs.

    I have now have the programs and test data running thru from prog 1 to prog 4. Just awaiting return of print outs from computeach.

    prog 1 your input file is text, the output file may be in text or binary. The only stipulation is that the input file for program 1 is text and the output file from 3 to 4 is in binary. you can use what ever format - text or binary in between.

    my programs run input text to output binary program 1.
    input binary to output binary prog 2.
    input binary to output binary prog 3.
    prog 4 only reads the input file to print the report.

    use fwrite(&all_recs, sizeof(RECORDS), 1, fp);
    use fread(&all_recs, sizeof(RECORDS), 1, fp)

  14. #14
    Registered User breed's Avatar
    Join Date
    Oct 2001
    Posts
    91
    Thanx BigTam youve just answered two questions taht i was goig to ask at C.I.L. in one go.

    .......... you should get a job at C.I.L, your more help than they are anyways.

    I'm going to phone them first thing tomorrow to get onto the prep course (can't wait for the handouts...hope there not more pamphlets though )

    Iv'e finished prog 1 started prog 2, should i open the validated file in binary?

    O'h by the way i think i'll wait a couple of weeks after the prep course before submitting any progs
    Before you judge a man, walk a mile in his
    shoes. After that, who cares.. He's a mile away and you've got
    his shoes.
    ************William Connoly

  15. #15
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Ho Breed, sent you an e-mail okay.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. read txt file as binary then convert to text
    By 911help in forum C Programming
    Replies: 2
    Last Post: 01-04-2008, 05:29 AM
  3. binary text file
    By spanker in forum C Programming
    Replies: 7
    Last Post: 12-28-2007, 01:10 AM
  4. how to convert a text file to a .dat file
    By Linette in forum C++ Programming
    Replies: 11
    Last Post: 02-25-2002, 04:58 AM

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