Thread: Write File to struct

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

    Write File to struct

    Code:
    void printtable(struct country *array)
    {
      for (int i = 0; array.name != NULL; i++) {  //Moving through the array of structs until NULL character.
        printf("%s %d %d %d\n", array.name, array.medals.gold, array.medals.silver,
               array.medals.bronze);
      }
    }
    
    void save_table(struct country *p, char *name)
    {
    
      char *filename = malloc(sizeof(name));
      strcpy(filename, name);
    
      FILE *file;
      file = fopen(filename, "w");
    
      fwrite(&p, sizeof(struct country), 1, file);
      fclose(file);
    
    }
    
    void load_table(struct country *p, char *name)
    {
    
      char *filename = malloc(sizeof(name));
      strcpy(filename, name);
    
      FILE *file;
      file = fopen(filename, "r");
    
      if (file != NULL) {
        while (1) {
          if (feof(file)) {
            printf("File Loaded Successfully!\n");
            break;
          } else {
            fscanf(file, "%s %d %d %d", p->name, &(p->medals.gold),
                   &(p->medals.silver), &(p->medals.bronze));
          }
        }
    
      } else {
        printf
            ("File failed to open due to either wrong name input, or nonexisting file.\n");
        return;
      }
    
      fclose(file);
    }
    
    int main()
    {
    
      struct country *array = malloc(sizeof(struct country));
      array[0].name = NULL;         //Initialize array
    
      char input[80];               //User input line
      char name[20];                //String for handling the name input
      int number = 0;               //Keeping track of the number of countries
    
      printf("Enter country and medals\n");
      printf("\n");
    
      while (1) {                   //Loops forever until "break" command
    
        fgets(input, sizeof(input), stdin); //Gets input from user
    
        if (input[0] == 'A') {
          sscanf(input, "%*c %s", name);  //Reads input, ignoring the first "command" character
          array = add_country(array, name);
          if (array == NULL) {
            printf("\nCreating country failed");
          } else {
            number++;               //Increases the number of countries
          }
    
        } else if (input[0] == 'M') {
          int g, s, b;              // Gold, Silver and Bronze medal count;
          sscanf(input, "%*c %s %d %d %d", name, &g, &s, &b); //Reads input, ignoring the first "command" character
          update_medals(array, name, number, g, s, b);
    
        } else if (input[0] == 'L') {
          printtable(array);
    
        } else if (input[0] == 'W') {
          sscanf(input, "%*c %s", name);  //Reads input, ignoring the first "command" character
          save_table(array, name);
    
        } else if (input[0] == 'O') {
          sscanf(input, "%*c %s", name);  //Reads input, ignoring the first "command" character
          load_table(array, name);
    
        } else if (input[0] == 'Q') {
          free(array);
          printf("Exiting program.\n");
          break;
        }
      }
      return 0;
    }
    I'm trying to read my array structs to a file with the command "W filename" and then load the file (write the file to a struct) with the command "O filename". A problem occurs when I try to print the table after I've loaded the file. The first character prints something entirely random, however the rest of the content are right.
    For example, if my input is like this:

    A USA
    A CANADA
    W FILE
    O FILE
    L

    It's supposed to print out:

    USA 0 0 0
    CANADA 0 0 0

    However, it prints:

    (random character) 0 0 0
    CANADA 0 0 0
    Last edited by Salem; 04-14-2020 at 01:45 PM. Reason: Removed crayola

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,128
    Code:
      char *filename = malloc(sizeof(name));
      strcpy(filename, name);
     
      FILE *file;
      file = fopen(filename, "r");
    Just fopen(name,"r") and save yourself the bother of making a mess of allocating the space for a string you never release.
    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
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,875
    Code:
      char *filename = malloc(sizeof(name));
    How big do you thing sizeof(name) is going to be? Remember that "name" is not an array in that function, it is a pointer to a char.

    Try running this small program..
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void anotherFunction(char *banana)
    {
        printf("In another function: %d\n", sizeof(banana));
    }
    
    int main(void)
    {
        char apple[] = "1234567890";
    
        printf("In main: %d\n", sizeof(apple));
    
        anotherFunction(apple);
    
    
        return EXIT_SUCCESS;
    }
    Fact - Beethoven wrote his first symphony in C

  4. #4
    Registered User
    Join Date
    Apr 2020
    Posts
    5
    Thank you guys, it helped with my other memory issue, but not with the problem I initially had, however I managed to figure it out by looking upat how writing file with structs actually works!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Write and read struct to txt file
    By Heisenberg800 in forum C Programming
    Replies: 1
    Last Post: 11-28-2017, 12:49 PM
  2. Write to struct
    By john7 in forum C Programming
    Replies: 2
    Last Post: 07-14-2014, 06:41 AM
  3. Using binary write to save a struct
    By skan in forum C++ Programming
    Replies: 4
    Last Post: 08-14-2013, 06:57 AM
  4. Replies: 52
    Last Post: 05-11-2013, 03:17 PM
  5. multiway read\write struct
    By quantt in forum C Programming
    Replies: 2
    Last Post: 02-02-2009, 10:13 AM

Tags for this Thread