将数据结构保存到文本文件

时间:2013-12-17 16:13:03

标签: c data-structures save

我正在尝试实现一个保存系统,它允许我保存用户输入的用户在switch语句中输入的“数据包”结构的数据。输入的每条记录都存储在通过纯文本行分隔的单个文件中。它还应该提示用户他们想要命名文件,然后程序应该指示已经保存到文件的记录数,最后如果没有输入保存文件的名称,它应该返回主菜单。 / p>

从底部的void save函数可以看到,我试图实现这个保存系统,但是当我运行程序并选择S将记录保存到文件时,它只是在我输入一个名称后崩溃文件名。所以如果有人能帮助我,那就太好了。

更新

通过调试器运行程序后,我得到以下错误

更新

修正了错误的错误,但是在输入文件的文件名时程序也会崩溃,而文件也会保存数据。

 #include <stdio.h>          //library including standard input and output functions
 #include <stdlib.h>         //library including exit and system functions used below
 #include <string.h>         //library including string functions used



 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));

        do{

    system("cls");
    puts("Please enter an option:\n");
    puts("'A' Add a packet:\n");
    puts("'D' to Display the Packet List:\n");                 // The Menu system
    puts("'S' to Save the Packets to a file:\n");
    puts("'C' to Clear the list of current saved packets:\n");
    puts(" or X to exit the program...\n");

    //wait for user input
    scanf("%c", &choice);   //take the first char of user input and assing the value to
                            //the variable choice using the address of (&) the variable
    if(choice == '\n')      //check to see that the character is not \n left over from the
        scanf("%c", &choice);   //previous choice made, if it is then we need to scan the input again

    switch (choice)
                    {
                        case 'A': system("cls"); //clear the screen

                        if(NetworkPacket==50)
                                {
                                    printf("No more network packets can be added");   // if statement giving the limit of 50 packets allowed to be added
                                    getch();        // User must press a key to continue
                                    continue;
                                }
                        else{
                                printf("\n****Adding a packet*****\n");
                                printf("Where is the packet from?\n");
                                scanf("%i", &s[NetworkPacket].source);
                                printf("Where is the packet going?\n");
                                scanf("%i", &s[NetworkPacket].destination);
                                printf("What type is the packet?\n");
                                scanf("%i", &s[NetworkPacket].type);                     // collecting the data of the packet inputted by the user
                                printf("What is the packet's port?\n");
                                scanf("%i", &s[NetworkPacket].port);
                                printf("Enter up to 50 characters of data.\n");
                                scanf("%s", s[NetworkPacket].data);
                                NetworkPacket++;
                            }break;

                        case 'D': system("cls"); //clear the screen
                                printf("\nDisplaying Infomation\n");

                                if(NetworkPacket==0)            // if statement stating to the user no records are shown if none are avalible
                                    {
                                        printf("no records yet, Please press any key to revert back to the main menu\n");
                                        getch();     // User must press a key to continue
                                        continue;
                                    }
                                else{
                                for(ii = 0; ii < NetworkPacket; ii++)
                                        {    // adds a 1 onto the NetworkPacket counter keeping a tally on the number of records stored.
                                            printf("\nSource: %d", s[ii].source);
                                            printf("\nDestination: %d", s[ii].destination );
                                            printf("\nType : %d", s[ii].type);// if statement giving the limit of 50 packets allowed to be added
                                            printf("\nPort : %d", s[ii].port);
                                            printf("\nData: %s\n---\n", s[ii].data);
                                        }getch();
                                    } break;

                        case 'S':
                            system("cls"); //clear the screen
                            save(NetworkPacket, records); //S was chosen so use the Save function
                        break;                       //the while condition is True so break the switch and loop around

                        case 4: break;
                        case 5: break;

                         default:system("cls"); printf("%c is not an option\n Try again...\n", choice);  // this message is shown if user doesn't input of one the case statment letters.


                         }
                         }while(choice!='X' );  // exits the program

                      return 0;

}


 void save(int rCount, struct packet *NetworkPacket){
  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<rCount;i++){
          fprintf(recordFile,"%04d %04d %04d %04d %s\n",
                  NetworkPacket[i].source,
                  NetworkPacket[i].destination,
                  NetworkPacket[i].type,
                  NetworkPacket[i].port,
                  NetworkPacket[i].port,
                  NetworkPacket[i].data);
      }
      fclose(recordFile);   //close the file
  }

}

2 个答案:

答案 0 :(得分:2)

  case 'S': break;   <---- you have a break just after the case definition try remove it
   system("cls"); //clear th

除了'S'以外的其他情况? 以及您应该使用fgets代替scanf的建议。

答案 1 :(得分:0)

好的我已经弄清楚如何修复调试器错误,但主要问题是,当提示我为保存文件选择文件名时,程序崩溃

 line 5: warning: "struc packet" declared inside parameter list

所以这发生了,因为我在一个函数中声明了struc数据包而没有首先声明什么是struc数据包。但现在已经修复了

 line 22: warning: assignment makes integer from pointer without a cast

我通过给它指向Struc数据包数据

的地址的实际指针来解决这个问题
line 89: warning: passing arg 2 of 'save' makes pointer from integer without a cast

与上述相同的解决方案。

我现在将更新代码