我正在用C编写程序,并尝试将结构数组保存到文件中。 我的意图是初始化一个结构数组并将其保存到一个文件中。此外,我想修改struct-entry 1,struct-entry 2,struct-entry 3等的条目,但条目不会写入文件。甚至似乎没有任何结构的数组。在C中的文件结构数组中写入条目C
我将不胜感激任何帮助,因为我想不通,为什么数组没有写入文件。
谢谢 Threx
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct liste {
unsigned int code;
unsigned int activ;
};
int main()
{
int z;
printf("Enter Index: "); /* Data should fill the z-th entry in array of structures */
scanf("%d",&z);
FILE *mrp;
struct liste bauteil[5]; /* Array with 5 structs for 5 different entries */
mrp = fopen("aaa.txt","w+b");
printf("Number of entry is: %d\n",z);
printf("Enter code: ");
scanf("%d",&bauteil[z].code);
bauteil[z].activ=77777; /* activ entry contains 77777 */
fseek(mrp, z * sizeof(struct liste), SEEK_SET);
fwrite(&bauteil[],sizeof(bauteil),1,mrp);
fclose(mrp);
return 0;
}
是否该文件已经存在,你的程序开始前?或者你的程序应该在填写条目时创建文件? – 2013-04-11 19:53:25
'fwrite(&bauteil [],sizeof(bauteil),1,mrp);'甚至没有编译。这是一个复制错误? (它应该是'fwrite(&bauteil [z],sizeof(bauteil),1,mrp);'要编译,但实际大小参数应该是'sizeof bauteil [0]')。 – 2013-04-11 19:53:59
@Scott:在填充它之前应该存在该文件,并且稍后必须填写/修改struct-entries(例如,使用bauteil [2] .code = 123)。 – Threx 2013-04-11 20:19:45