title: Saving data structure to a text file
body: <p>I am trying to implement a save system which allows me to save the user entered data of the "packet" structure that the user entered in the switch statement. Each record entered is stored in a single file separated via lines in plain text. It should also prompt the user what they would like to name the file, then the program should indicate how many records have been saved to the file, finally if no name is entered for the save file it should go back to the main menu.</p>
  
  <p>as you can see from the void save function at the bottom, i have tried to implement this save system but when i run the program and choose S to save the records to the file it simply crashes the program after I enter a name for the file name. So if anyone could help me with this, that would be great.</p>
  
  <pre><code>struct packet{
      int source;
      int destination;
      int type;               // Varibles for the structure
      int port;
      char data[50];
      char * filename;
  };
  
  void save(int, struct packet*); //function to save the records stored to a file
  int main ()
  {
  struct packet s[50];         //Array for structure input
  char choice;
  int NetworkPacket = 0, ii = 0;
  int recordCount = 0;
  struct packet *records;
  struct packet *temp;
  records = malloc(sizeof(struct packet));
  </code></pre>
  
  <p>case statement for choosing to save the file</p>
  
  <pre><code> case 'S':
              system("cls"); //clear the screen
              save(NetworkPacket, records); //S was chosen so use the Save function
   break;
  </code></pre>
  
  <p>the save function </p>
  
  <pre><code> void save(int rCount, struct packet *records){
    FILE *recordFile;                 //file handle
    char fileName[30] = { '\0'};      //string to store the file name
    int i;
  
    puts("Enter a filename to save the records :");   //ask the user for the filename
    scanf("%s", fileName);                            //store the filename: data input should be checked
                                                      //here in your program
  
    //try and open the file for writing and react accordingly if there is a problem
    if((recordFile = fopen(fileName,"w"))==NULL){
        printf("Couldn't open the file: %s\n",fileName);
        exit(1);
    }
    else{ //the file opened so print the records array of packets to it
        for(i=0;i&lt;rCount;i++){
            fprintf(recordFile,"%04d %04d %04d %04d %s\n",
                    records[i].source,
                    records[i].destination,
                    records[i].type,
                    records[i].port,
                    records[i].port,
                    records[i].data);
        }
        fclose(recordFile);   //close the file
    }
  
  }
  </code></pre>