Thread: Updating in a sequential file?

  1. #1
    Registered User Ronnyv1's Avatar
    Join Date
    Mar 2009
    Posts
    1

    Updating in a sequential file?

    ok it seems im in a bit of distress right now, i can't seem to figure out how to update/replace data in my file. Maybe having a glance at what i have may help so here it is below:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX_FIRSTNAME_LENGTH  25
    #define MAX_LASTNAME_LENGTH   25
    #define TRUE                   1
    #define FALSE                  0
    
    
    /* Student Structure */
    struct stdntbio
    { 
      int age;
      float gpa;
      char firstname[MAX_FIRSTNAME_LENGTH];
      char lastname[MAX_LASTNAME_LENGTH];
    };
    
    /* Course grade structures */
    struct CourseGrade
    {
      struct stdntbio bio;
      float mth;
      float eng;
      float sub1;
      float sub2;
      float sub3;
    };
    
    /* Vars */
    FILE *ptrFile = NULL;                                 
    char *filename = "studentdb.txt";                
    char choice = 'n';                             
    
    /* Function prototypes */
    struct CourseGrade input_studentinfo();
    struct stdntbio input_bio();  
    void show_student(struct CourseGrade student);
    struct CourseGrade find_student(struct stdntbio bio);
    void add_student();
    void delete_student(struct stdntbio bio);
    void list_students(); 
    void display_menu();
    int main()
    {
        printf("\n       ************************************");
        printf("\n          WELCOME TO THE STUDENT DATABASE");
        printf("\n       ************************************");
        
      display_menu(); 
      
      for(;;)
      {
        printf("\nEnter a number to select an option: ");
        scanf(" %c", &choice);
        switch(choice)
        {
          case '1':                                     
            add_student();
            break;
          case '2':                                     
            delete_student(input_bio());
            break;
          case '3':                                    
            find_student(input_bio());
            break;
          case '4':                                     
            list_students();
            break;
          case '5':                                     
            return choice;
          default:
            printf("\nBad Input!");
            display_menu();
            break;
        }
      }
     }
      
    struct CourseGrade input_studentinfo()
    {
      struct CourseGrade student;    
      student.bio = input_bio();
        printf("Enter Grade for MTH: ");
      scanf("%f",&student.mth);
        printf("\nEnter Grade for ENG: ");
      scanf("%f",&student.eng);
        printf("\nEnter Grade for SUB1: ");
      scanf("%f",&student.sub1);
        printf("\nEnter Grade for SUB2: ");
      scanf("%f",&student.sub2);
        printf("\nEnter Grade for SUB3: ");
      scanf("%f",&student.sub3);
      return student;
    }
    
    /* Displays all student data, bio and grades */
    void display_student(struct CourseGrade student)
    {
      printf("\n%s %s %d  %.0f %.0f %.0f %.0f %.0f", 
    student.bio.firstname,student.bio.lastname,student.bio.age, student.mth,student.eng,
    student.sub1,student.sub2,student.sub3);
    }
    
    /* Insert a student and their grades */
    void add_student()
    {
      struct CourseGrade student;
    
      if((ptrFile = fopen(filename, "a+")) == NULL) 
      {
        printf("%s Failed to open for writing.", filename);
        system("exit");
      }
      student = input_studentinfo();                 
      fwrite(&student, sizeof student, 1, ptrFile);
      fclose(ptrFile);                             
      printf("\nSuccess! Student Added");
    }
    
    /* take in a student from the user and make a structure for it */
    struct stdntbio input_bio()
    {
      struct stdntbio bio;
        printf("Enter a First name: ");
        scanf(" %s", &bio.firstname);
        printf("Enter a Last name: ");
        scanf(" %s", &bio.lastname);
        printf("Enter an Age: ");
        scanf(" %d", &bio.age);
      return bio;
    }
    
    void delete_student(struct stdntbio bio)
    {
      FILE *pNewFile = NULL;
      char *pnewfilename = NULL;
      struct CourseGrade student;
    
      if((ptrFile = fopen(filename, "r")) == NULL)       /* Open current file to read it */
      {
        printf("File failed to open for reading.", filename);
        abort();
      }
        pnewfilename = tmpnam(NULL);
                                                         /* Create temporary file name      */
      if((pNewFile = fopen(pnewfilename, "w")) == NULL)
      {
        printf("%s Failed to open for writing.", pnewfilename);
        fclose(ptrFile);
        abort();
      }
      
        /* Copy existing file contents to temporary file, leaving deleted students */
      for(;;)
      {
        fread(&student, sizeof student, 1, ptrFile);    
        if(feof(ptrFile))                                
          break;                                         
    
        if(equals(bio, student.bio))              
        {
          printf("\nFound a record:");              
          display_student(student);
          printf("\nAre you sure you want to delete? (y or n)? ");
          scanf(" %s", &choice);
          if((choice) == 'y')               
            continue;                              
        }
        fwrite(&student, sizeof student, 1, pNewFile);  
      }
      fclose(ptrFile);
      fclose(pNewFile);
    
      if((pNewFile = fopen(pnewfilename, "r")) == NULL) 
      {
        printf("Error opening %s for reading.", pnewfilename);
        abort();
      }
      if((ptrFile = fopen(filename, "w"))==NULL)           
      {
        printf("Error opening %s for writing.", filename);
        abort();
      }
    
      /* Copy contents of new temporary file back to old file          */
      
      for(;;)
      {
        fread(&student, sizeof student, 1, pNewFile);
        if(feof(pNewFile))                            
          break;                                      
    
        fwrite(&student, sizeof student, 1, ptrFile); 
      }
      fclose(ptrFile);                    
      fclose(pNewFile);                    
      remove(pnewfilename);               
      printf("Delete complete.");
    }
    
    /* List all the records in the file */
    void list_students()
    {
      struct CourseGrade student;
      int file_empty = TRUE; 
    
      if((ptrFile = fopen(filename, "r")) == NULL)       
      {
        printf("Error opening %s for reading.", filename);
        abort();
      }
      
      /* Listing the file contents */
      for(;;)
      {
        fread(&student, sizeof student, 1, ptrFile);
        if(feof(ptrFile))
          break;
        file_empty = FALSE;              
        display_student(student);        
      }
      fclose(ptrFile);                
    
      /* Check whether there were any students */
      if(file_empty)
        printf("The file has no students.\n");
      else
        printf("\n");
    }
    
    /* Displays the options that can be done */
    void display_menu()
    {  
        printf("\n    Please select an option from the menu below:\n\n"
        "\n1 - Add a new student."
        "\n2 - Delete a student."
        "\n3 - Find a student."
        "\n4 - Display all students stored."
        "\n5 - Exit.");
    }
    
    /* Find students corresponding to a given name */
    struct CourseGrade find_student(struct stdntbio bio) 
    {
      struct CourseGrade student;
      int student_found = FALSE;                   
    
      if((ptrFile = fopen(filename, "r")) == NULL)      
      {
        printf("Error opening %s for reading.", filename);
        abort();
      }
      
    /* Search the students from the file */
      for(;;)
      {
        fread(&student, sizeof student, 1, ptrFile); 
        if(feof(ptrFile))
          break;
       if(equals(bio,student.bio))             
       {
         if(!student_found)                        
         {
           student_found = TRUE;                       
           printf("Credit(s) for this student are:");
         }
         printf("\n MTH: %.1f \n Eng: %.1f \n Sub1: %.1f \n Sub2: %.1f \n Sub3: %.1f\n\n",
    student.mth,student.eng,student.sub1,student.sub2,student.sub3);   
       }
      }
      fclose(ptrFile); 
                                      
      if(!student_found)
        printf("Student was not found.\n");
      else
        printf("\n");
    }
    
    /* Compare two sets of data */
    int equals(struct stdntbio bio1, struct stdntbio bio2)
    {
      return (strcmp(bio1.firstname, bio2.firstname)==0) && (strcmp(bio1.lastname, bio2.lastname)==0);
    }
    Trying to update the data of a student, i know i need to update the structure but i don't know where to start.
    As you can see i've gotten quite a bit done and alot more to go this is just a stepping stone i've yet to cross.
    Last edited by Ronnyv1; 03-24-2009 at 04:00 PM. Reason: extra info

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    struct CourseGrade input_studentinfo()
    {
      struct CourseGrade student;    
      student.bio = input_bio();
        printf("Enter Grade for MTH: ");
      scanf("%f",&student.mth);
        printf("\nEnter Grade for ENG: ");
      scanf("%f",&student.eng);
        printf("\nEnter Grade for SUB1: ");
      scanf("%f",&student.sub1);
        printf("\nEnter Grade for SUB2: ");
      scanf("%f",&student.sub2);
        printf("\nEnter Grade for SUB3: ");
      scanf("%f",&student.sub3);
      return student;
    
    //You can't return a whole struct. Instead, return a pointer to that struct.
    }
    
    /* Displays all student data, bio and grades */
    void display_student(struct CourseGrade student)
    {
      printf("\n%s %s %d  %.0f %.0f %.0f %.0f %.0f", 
    student.bio.firstname,student.bio.lastname,student.bio.age, student.mth,student.eng,
    student.sub1,student.sub2,student.sub3);
    }
    
    /* Insert a student and their grades */
    void add_student()
    {
      struct CourseGrade student;
      student * ptrS = &student;
    
      if((ptrFile = fopen(filename, "a+")) == NULL) 
      {
        printf("%s Failed to open for writing.", filename);
        system("exit");
      }
      student = input_studentinfo();                 
    //you want to replace "student" in the line immediately above this one, with a 
    //pointer to student, so:
       ptrS = input_studentinfo();
       fwrite(ptrS, sizeof student1, ptrFile);   
    
    // fwrite(&student, sizeof student, 1, ptrFile);
      fclose(ptrFile);                             
      printf("\nSuccess! Student Added");
    }
    
    /* take in a student from the user and make a structure for it */
    struct stdntbio input_bio()
    {
      struct stdntbio bio;
        printf("Enter a First name: ");
        scanf(" %s", &bio.firstname);
        printf("Enter a Last name: ");
        scanf(" %s", &bio.lastname);
        printf("Enter an Age: ");
        scanf(" %d", &bio.age);
      return bio;
    //same here. bio is a struct, not a pointer. Make a pointer and return it, instead.
    }
    Use a pointer to bring back what you want from an updated or new student struct function. Then use that pointer to fwrite the struct to the file.
    Last edited by Adak; 03-24-2009 at 04:45 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  4. Hmm....help me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM