gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:47:44 25 4
gpt4 key购买 nike

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

正如你从底部的void保存功能中看到的,我尝试实现这个保存系统,但是当我运行程序并选择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
}

}

最佳答案

格式字符串中还需要一个 %d 修饰符 - 有五个整数,但只有四个 %d

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

关于c - 将数据结构保存到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com