ama*_*hth 22 c file-io structure
是否可以将整个结构写入文件
例:
struct date {
char day[80];
int month;
int year;
};
Run Code Online (Sandbox Code Playgroud)
pin*_*her 33
是否可以将整个结构写入文件
您的问题实际上是将结构实例写入文件.
fwrite函数来实现此目的.sizeof 第二个参数中的每个对象binary mode.当您在小端系统中编写/读取以及在大端系统中读取/写入时,请注意字节顺序,反之亦然.阅读how-to-write-endian-agnostic-cc-code
struct date *object=malloc(sizeof(struct date));
strcpy(object->day,"Good day");
object->month=6;
object->year=2013;
FILE * file= fopen("output", "wb");
if (file != NULL) {
fwrite(object, sizeof(struct date), 1, file);
fclose(file);
}
Run Code Online (Sandbox Code Playgroud)你可以用同样的方式阅读它们....使用 fread
struct date *object2=malloc(sizeof(struct date));
FILE * file= fopen("output", "rb");
if (file != NULL) {
fread(object2, sizeof(struct date), 1, file);
fclose(file);
}
printf("%s/%d/%d\n",object2->day,object2->month,object2->year);
Run Code Online (Sandbox Code Playgroud)