2013-12-17 30 views
-1

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

从底部的void save函数中可以看到,我试图实现这个保存系统,但是当我运行程序并选择S将记录保存到文件中时,它只是在我进入文件名称。所以如果有人能够帮助我,那会很棒。

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

case语句的选择保存文件

case 'S': 
      system("cls"); //clear the screen 
      save(NetworkPacket, records); //S was chosen so use the Save function 
break; 

保存功能

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<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 
    } 

} 
+0

建立一个de错误版本,并在调试器中运行。它会停在崩溃的位置,让你检查并遍历函数调用堆栈。当您将调用堆栈放到代码中发生崩溃的位置时,您将能够检查变量的值。 –

+0

之前要看的东西,可能是'rCount'('NetworkPacket')的值,并确保你有足够的分配内存给'records'指针(现在你似乎只分配一个'packet'结构)。 –

+0

你确定记录[i] .data是一个以空字符结尾的字符串吗? –

回答

0

有格式字符串需要一个更为%d修饰符 - 有五个整数,但只有4%d s

fprintf(recordFile,"%04d %04d %04d %04d %04d %s\n", 
             ^^^^