Like Tree1Likes
  • 1 Post By jimblumberg

Help with Recording struct to a file

This is a discussion on Help with Recording struct to a file within the C Programming forums, part of the General Programming Boards category; **First of all, sorry about my English** I'm doing this code and i want to record the struct to a ...

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    5

    Help with Recording struct to a file

    **First of all, sorry about my English**

    I'm doing this code and i want to record the struct to a file, but it's not working... When i open the programme again the information that i thought i had saved, isn't there.
    I think i know the err, i am recording just the pointer and not the information, but i don't know what i should do.
    Can someone, please, help me?
    Thanks a lot!

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <ctype.h>
    
    #define MAX1 1000
    
    
    //////////////////////////////STRUCT
    
    struct book{
    char nameofbook[17];
    int area;
    char autor[60];
    char edit[20];
    };
    
    
    /////////////////////////////////////////////////////////INSERT BOOKS
    void insertBooks(struct book books[MAX1], int *contbooks){
     int ii;
     int *pont;
    
    FILE *fptr;
    FILE *keep1;
    
    
    ///////////////////READING POSITION
    keep1=fopen("keeppointer1.txt","r");
    int x=0;
    
    while(fscanf(keep1, "%i",  &x) > 0)
    {
       fprintf(keep1, "%i", x);
       printf("\n%i", x);
       printf("\nVALUE pointer");
    }
    
    
    
    ///////////////////WRITING INFO
    if ((fptr = fopen("filekeeping", "wb")) == NULL){
    printf("\nErr");
     
    }else{
    contbooks=&x;
       do{
       printf("\n Name of the book: ");
       gets(books[*contbooks].nameofbook);
       
       }while(strlen(books[*contbooks].nameofbook)==0);
       fwrite(&books, sizeof(book), 1, fptr);
       
    *contbooks=*contbooks+1;
    fclose(fptr);
    }
    
    ///////////////////READIND INFO
    if ((fptr = fopen("filekeeping", "rb")) == NULL)
        printf("\nErr");
    else{
      while(fread(&books, sizeof(book), 1, fptr) == 1){
      for(ii = 0; ii <=*contbooks-1; ii++){
      printf("\nName: %s\n",books[ii].nameofbook);
         }
        }
        fclose(fptr);
    }
    
    
    ///////////////////WRITING POINTER
    keep1=fopen("keeppointer1.txt","w");
    if(keep1==NULL){
    printf("\n erro");
    }else{
    pont=contbooks;
    fprintf(keep1, "%i", *pont);
    //printf("\n%i", *pont);
    fclose(keep1);
    }
    
    ///////////////////READING POINTER
    if ((fptr = fopen("keeppointer1.txt", "r")) == NULL){
    printf("\nErro");
    }else{
    while (!feof(keep1)){
    fscanf(keep1,"%i",&*pont);
    printf("\n%i",*pont);
    } 
    }
    fclose(keep1);
    
    
    
    };////END
    
    
    
    ////////////////////////////////////////////////
    main(){
    
    struct book books[MAX1];
    int opt,contbooks=0;
    
    
    do{
       printf("\n\n");
       printf("\n Option?");
       printf("\n 1 - Insert Books");
       printf("\n Option: ");
       scanf("%d", &opt);
       fflush(stdin);
       
       switch(opt){
       
       case 1:{
       insertBooks(books, &contbooks);
      
       break;
       }
       
                
       case 0:{
       break;
       }
                   
       default:{
       printf("\n \n =====INVALID===== \n \n");
       break;
       }
       }
    }while (opt!=0);
    
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,674
    Are you compiling this C program with a C++ compiler? When I try to compile this C program I get the following errors:
    main.c||In function ‘insertBooks’:
    main.c|53|error: ‘book’ undeclared (first use in this function)
    main.c|53|note: each undeclared identifier is reported only once for each function it appears in
    Next you are opening and closing your file several times in this function, why? You also need to study the documentation for fopen() and pay particular attention to the mode string. What happens to your file when you open the file with the "w" open mode?

    You also need to find an indentation style you like and use it consistently.


    Jim

  3. #3
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    227
    Code:
    ///////////////////READING POSITION
    keep1=fopen("keeppointer1.txt","r");
    int x=0;
     
    while(fscanf(keep1, "%i",  &x) > 0)
    {
       fprintf(keep1, "%i", x);
       printf("\n%i", x);
       printf("\nVALUE pointer");
    }
    For Pete's sake, check the return values of your API calls, people! What happens in your program if fopen() failes to open the specified file (because maybe it's just not there)?? That's right, your program crashes because you just go ahead and try to write stuff to it anyway. Read the documentation of fopen() and understand that, if fopen() fails, it returns a null pointer. Then, in your code, check the pointer returned by fopen() and, if it is null, do something about that (print an error message to screen and abort the program or something like that). Do not just assume on blind faith that API calls are always going to succeed!

    The next problem in your code is that you try to open your file with READ ACCESS (that's what the "r" flag means) and then try to WRITE to it using fprintf().

  4. #4
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    227
    I've loaded your code in Visual Studio and used the automatic code reformatting option to reindent your code. Also fixed the 2 problems I've mentioned (although there may be lots more in your code ... I didn't check the whole thing).

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <ctype.h>
    
    #define MAX1 1000
    
    
    //////////////////////////////STRUCT
    
    struct book{
        char nameofbook[17];
        int area;
        char autor[60];
        char edit[20];
    };
    
    
    /////////////////////////////////////////////////////////INSERT BOOKS
    void insertBooks(struct book books[MAX1], int *contbooks){
        int ii;
        int *pont;
    
        FILE *fptr;
        FILE *keep1;
    
    
        ///////////////////READING POSITION
        keep1=fopen("keeppointer1.txt","a");
    
        if ( ! keep1 )
        {
            printf( "OMG!! Couldn't open the file!!!\n" );
            exit( 1 );
        }
    
        int x=0;
    
        while(fscanf(keep1, "%i",  &x) > 0)
        {
            fprintf(keep1, "%i", x);
            printf("\n%i", x);
            printf("\nVALUE pointer");
        }
    
    
    
        ///////////////////WRITING INFO
        if ((fptr = fopen("filekeeping", "wb")) == NULL){
            printf("\nErr");
    
        }else{
            contbooks=&x;
            do{
                printf("\n Name of the book: ");
                gets(books[*contbooks].nameofbook);
    
            }while(strlen(books[*contbooks].nameofbook)==0);
            fwrite(&books, sizeof(book), 1, fptr);
    
            *contbooks=*contbooks+1;
            fclose(fptr);
        }
    
        ///////////////////READIND INFO
        if ((fptr = fopen("filekeeping", "rb")) == NULL)
            printf("\nErr");
        else{
            while(fread(&books, sizeof(book), 1, fptr) == 1){
                for(ii = 0; ii <=*contbooks-1; ii++){
                    printf("\nName: %s\n",books[ii].nameofbook);
                }
            }
            fclose(fptr);
        }
    
    
        ///////////////////WRITING POINTER
        keep1=fopen("keeppointer1.txt","w");
        if(keep1==NULL){
            printf("\n erro");
        }else{
            pont=contbooks;
            fprintf(keep1, "%i", *pont);
            //printf("\n%i", *pont);
            fclose(keep1);
        }
    
        ///////////////////READING POINTER
        if ((fptr = fopen("keeppointer1.txt", "r")) == NULL){
            printf("\nErro");
        }else{
            while (!feof(keep1)){
                fscanf(keep1,"%i",&*pont);
                printf("\n%i",*pont);
            }
        }
        fclose(keep1);
    
    
    
    };////END
    
    
    
    ////////////////////////////////////////////////
    int main(void){
    
        struct book books[MAX1];
        int opt,contbooks=0;
    
    
        do{
            printf("\n\n");
            printf("\n Option?");
            printf("\n 1 - Insert Books");
            printf("\n Option: ");
            scanf("%d", &opt);
            fflush(stdin);
    
            switch(opt){
    
            case 1:{
                insertBooks(books, &contbooks);
    
                break;
                   }
    
    
            case 0:{
                break;
                   }
    
            default:{
                printf("\n \n =====INVALID===== \n \n");
                break;
                    }
            }
        }while (opt!=0);
    
    }
    Last edited by antred; 06-17-2012 at 07:04 AM.

  5. #5
    Registered User
    Join Date
    Jun 2012
    Posts
    5
    I use Dev-C to compile the program... And i am not getting any problems... I'm kinda new with programming C. I'm opening and closing the files to see If the information is being wrote correctly. I will erase it after the programme is finished.
    The Major problem is that i not being able to write the struct in the file.

    I think the problem is in this line:

    Code:
    fwrite(&books, sizeof(book), 1, fptr);
    Thanks for the help

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    2,674
    You do have several problems with your file writing. First Never use gets() this is a very unsafe program and it is easy to write past the end of your array. Always use a function that will only retrieve a certain number of characters, like fgets(). Next in the following snippet:
    Code:
    ///////////////////WRITING INFO
    if ((fptr = fopen("filekeeping", "wb")) == NULL){
    printf("\nErr");
      
    }else{
    contbooks=&x;
       do{
       printf("\n Name of the book: ");
       gets(books[*contbooks].nameofbook);
        
       }while(strlen(books[*contbooks].nameofbook)==0);
       fwrite(&books, sizeof(book), 1, fptr);
        
    *contbooks=*contbooks+1;
    fclose(fptr);
    }
    You are always erasing your file contents when you open your file. Is this really what you want?

    You really need to break the reading, writing, and user input into separate functions. Right now the way the program is written you erase the file every time you call this function, then try to write the entire array to the file every time.

    Your fwrite() is incorrect because books is an array, sizeof(book) is the size of one element of this array. If you want to re-write the entire array every time you call this function then you need the size of the entire array (sizeof(book) * TheNumberOfElements). However, in my opinion it would be better if you didn't erase the file every time and just added the new information to your existing file.

    Jim
    Last edited by jimblumberg; 06-17-2012 at 09:24 AM.
    stahta01 likes this.

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,793
    Code:
    while (!feof(keep1)){
        fscanf(keep1,"%i",&*pont);
        printf("\n%i",*pont);
    }
    Read: Why it's bad to use feof() to control a loop
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. struct within a struct, odd behavior accessing variables
    By John Gaden in forum C++ Programming
    Replies: 2
    Last Post: 02-28-2012, 05:19 AM
  2. Replies: 5
    Last Post: 06-30-2011, 03:24 PM
  3. Replies: 1
    Last Post: 05-12-2011, 01:02 AM
  4. 2 problems: Struct array and pointer + struct
    By v1n1c1u5 in forum C Programming
    Replies: 0
    Last Post: 12-13-2009, 04:38 PM
  5. struct holding data inside a linked list struct
    By icestorm in forum C Programming
    Replies: 2
    Last Post: 10-06-2009, 12:49 PM

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