Thread: Struct + File

  1. #1
    Registered User
    Join Date
    Nov 2020
    Posts
    5

    Struct + File

    Hi, I got this problem when I was running my code. I am a beginner in this field so it'd be great to know what is the problem in my code. The error is when I finished putting in my input, it could not read my input and my filename.txt stopped working.

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    typedef struct details
    {
        char plateNo[50];
        char vehicleType[50];
        char carBrand[50];
        int date;
        int driverID;
        char ticketNo[50];
    }details;
    
    
    
    
    int main ()
    {
        details b;
            
        FILE *fpwrite,* fpread;
        
        fpwrite - fopen ("data_test.txt", "w");    
        if( fpwrite == NULL )
        {
            printf("Error! File not found");
            exit(1);
        }
        newEntry :
         
        printf("\n---New Details---");
        
        printf("\nPlate No. : ");
        gets(b.plateNo);
        
        printf("\nVehicle Type : ");
        scanf("%s", &b.vehicleType);
        
        printf("\nCar Brand : ");
        scanf("%s", &b.carBrand);
        
        printf("\nDate : (example: DD/MM/YY) \n");
        scanf("%d", &b.date);
        
        printf("\nDriver ID : ");
        scanf("%d", &b.driverID);
        
        printf("\nTicket Issued : ");
        scanf("%d", &b.ticketNo);
        
        fflush (stdin);
        fwrite(&b,sizeof(b),10,fpwrite);
        fclose(fpwrite);
        
        fpread = fopen("data_test.txt", "r");
        while (fread(&b, sizeof(b),10,fpread) > 0)
            printf("%s\n %s\n %d\n %d\n %d\n",b.plateNo,b.vehicleType,b.carBrand,b.date,b.driverID,b.ticketNo);
        fclose(fpread);
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Don't use gets()
    Why gets() is bad / Buffer Overflows - Cprogramming.com

    Don't use fflush(stdin)
    Why fflush(stdin) is wrong - Cprogramming.com

    > fpwrite - fopen ("data_test.txt", "w");
    minus? really?

    > printf("\nDate : (example: DD/MM/YY) \n");
    > scanf("%d", &b.date);
    You're not going to fit some / separated string into a single integer.

    > printf("\nTicket Issued : ");
    > scanf("%d", &b.ticketNo);
    But ticket is a char array.

    > fwrite(&b,sizeof(b),10,fpwrite);
    Where did 10 come from?
    You only have 1 b, not 10 of them.

    Oh, it's a good idea to start with
    Code:
    typedef struct details
    {
        char plateNo[50];
    }details;
    Make a single element structure work, along with asking one question and printing one answer.
    When that works, then expand to further fields.

    A development process
    In short, don't try and solve the whole thing in one iteration.
    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
    Nov 2020
    Posts
    5
    Oh my gosh, goodness me.
    I got a lot of errors here and there, thank you so much

  4. #4
    Registered User
    Join Date
    Nov 2018
    Location
    Amberg in upper palatinate, Bavaria
    Posts
    66
    Hallo,

    Salem is right, you can use
    Code:
    scanf("%49[^\n]", b.plateNo);
    This line reads all character including the space(ASCII 32dec)
    The number 49 limits the length of the input to 49 Bytes to prevent a overflow.
    Example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void clpuf(void)
     {
     while (getc(stdin) != '\n')
        ;
     }
    
    int main()
    {
     int i;
     char c_posi[200],  c_nega[200];
    
     for (i = 0; i < 200; i++)
          c_posi[i] = c_nega[i] = 0;
    
     printf("Example Positiv- and negativ Liste with scanf\n");
    
     printf("\nPlease for example enter a String like \nexample.....: 123430abc  \nEnter string:  ");
    
    /**  reads only characters where between the braces, and finishes the inputwhen the first character was read in where not in this list */
     scanf("%[0123456789+-*/=]", c_posi);
     printf("The Input was:: %s \n\n", c_posi);
    
     /** clears keyboard buffer */
     clpuf();
    
     printf("\nPlease for example enter a String like \nexample.....: asdfgh123  \nEnter string:  ");
      scanf("%[^1234567890]", c_nega);
     printf("The Input was: %s \n\n", c_nega);
    
     clpuf(); /** clears keyboard buffer*/
    
     printf("\nPlease enter a string witch includes space-character\nEnter:  ");
     /** reads all characters, but not the newline-sign(Enter)*/
     scanf("%199[^\n]", c_nega);
     printf("The Input was: %s \n\n", c_nega);
    
     printf("End of Program\n");
    return EXIT_SUCCESS;
    }

  5. #5
    Registered User
    Join Date
    Nov 2018
    Location
    Amberg in upper palatinate, Bavaria
    Posts
    66
    Hi Syazzz

    here an example to write ONE set of details:
    Code:
     
    typedef struct details
    {
        char plateNo[50];
        char vehicleType[50];
        char carBrand[50];
        int date;
        int driverID;
        char ticketNo[50];
    }details;
     
     void clpuf(void)
     {
     while (getc(stdin) != '\n')
        ;
     }
    
     
     
     
    int main()
    {
        details b;
        char datname[100] = {0};
        FILE *fpwrite,* fpread;
        int watu = 21;
        
        strcpy(datname,"data_test.txt"); 
    
     do     
     switch (watu)
     {
       default:
             printf("\n---structreadrest\n");
             printf("\nEnd of Program............0\n");
             printf("\nread file.................2\n");
             scanf("%d", & watu); 
             clpuf();
           break;
      
      case 0:
             printf("\nEnd of Program\n");
             return 0;
           break;  
         
    
      case 1:
        //newEntry :
        printf("\n---New Details---");
         
        printf("\nPlate No. : ");
        scanf("%[^\n]", b.plateNo);
      
        clpuf();
         
        printf("\nVehicle Type : ");
        scanf("%[^\n]", b.vehicleType);
        
        clpuf();
             
        printf("\nCar Brand : ");
        scanf("%[^\n]", b.carBrand);
         
        clpuf(); 
         
        printf("\nDate : (example: DD/MM/YY) \n");
        scanf("%d", &b.date);
         
        clpuf(); 
         
        printf("\nDriver ID : ");
        scanf("%d", &b.driverID);
         
        clpuf(); 
         
        printf("\nTicket Issued : ");
        scanf("%[^\n]", b.ticketNo);
         
        clpuf();
        
        printf("\nTry to create %s\n", datname);
        fpwrite = fopen (datname, "w");    
        if( fpwrite == NULL )
        {
            printf("Error! File not found");
            return(0);
        }
        
        fwrite(&b,sizeof(struct details),1,fpwrite);
        fclose(fpwrite);
        watu = 21;
       break; 
        
    case 2: 
        printf("\nTry to read    %s\n", datname);     
        fpread = fopen(datname, "r");
        if (fpread == NULL) 
         { 
          printf("\nError open file\n"); 
          watu = 21;
          break; 
         } 
       
     while (fread(&b, sizeof(struct details),1, fpread))
        {  
         printf("Plate No.... :  %s\n",  b.plateNo);
         printf("Vehicle Type :  %s\n",  b.vehicleType); 
         printf("Car Brand... :  %s\n",  b.carBrand); 
         printf("Date ....... :  %d\n ", b.date);
         printf("Driver ID... :  %d\n",  b.driverID);
         printf("Ticket Issued:  %s\n",  b.ticketNo);  
        }
        fclose(fpread);
        
            
         watu = 21;
       break;  
       
       
     }while(watu != 0);
     printf("\nEnd of Program\n"); 
     return 0;   
    }
    the row
    Code:
    while(fread(&bc[i++], sizeof(struct buch3), 1, infile))
    writes 1 time a set of details.
    When you have a fixed number like 10, it could be happen that
    the Program writes any nonsens as data and you will have an error
    when you will try to read the file.

  6. #6
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    rusyoldguy & Syazzz:

    Instead of using:
    Code:
    scanf("%[^\n]", b.plateNo);
    I strongly urge the use of fgets() instead and then remove the newline form the end of the string.

    scanf() is fine for inputing numbers, but please use fgets() for strings. And please use #defines instead of "Magic Numbers"
    Code:
    #define DIM 50
    ...
    char plateNo[DIM];
    ...
    // Not
    ...
    char plateNo[50];
    ...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 11-21-2017, 10:48 AM
  2. Replies: 5
    Last Post: 01-19-2017, 11:03 AM
  3. Replies: 10
    Last Post: 10-14-2011, 01:31 PM
  4. from a struct to a binary file, to a struct again
    By starshiptrooper in forum C++ Programming
    Replies: 4
    Last Post: 10-07-2011, 09:37 AM
  5. getting file size from FILE* struct
    By duck-billed platypus in forum C++ Programming
    Replies: 3
    Last Post: 01-03-2002, 02:03 AM

Tags for this Thread