所以当我使用这个'保存'功能时,它似乎改变了我的结构中的数据,随机数字和图标。如果我不保存文件,那么结构内数据的完整性将保持原始输入。
我不确定错误的位置或者如何开始修复此错误,感谢您的帮助。
这是我的结构;
struct packet{ // declare structure for packet creation
int source;
int destination;
int type;
int port;
char data[51];
};
这是函数;
//Save the records to a file: follows the same principle as list but uses a file handle (pointer to a file)
//and fprintf to write to the file
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 packet 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].data);
}
fclose(recordFile); //close the file
}
}
答案 0 :(得分:2)
您如何知道结构数据已损坏?根据您的代码,我可以看到您的输出到文件将是错误的基于这一行:
fprintf(recordFile,"%04d:%04d:%04d:%04d:%s\n",&records[i].source,
&records[i].destination,
&records[i].type,
&records[i].port,
&records[i].data);
您的指针引用已关闭。假设你的程序的其余部分是正确的,只需删除领先&amp; s,我猜这解决了大部分问题,如果不是全部你的问题:
fprintf(recordFile,"%04d:%04d:%04d:%04d:%s\n",records[i].source,
records[i].destination,
records[i].type,
records[i].port,
records[i].data);