我正在尝试实现一个保存系统,它允许我保存用户输入的用户在switch语句中输入的“数据包”结构的数据。输入的每条记录都存储在通过纯文本行分隔的单个文件中。它还应该提示用户他们想要命名文件,然后程序应该指示已经保存到文件的记录数,最后如果没有输入保存文件的名称,它应该返回主菜单。 / p>
从底部的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 '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 :(得分:0)
格式字符串中还需要一个%d修饰符 - 有五个整数但只有四个%s
fprintf(recordFile,"%04d %04d %04d %04d %04d %s\n",
^^^^