C语言 在 c 中将结构写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16997141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing Structs to a file in c
提问by amarVashishth
Is it possible to write an entire struct to a file
是否可以将整个结构写入文件
example:
例子:
struct date {
char day[80];
int month;
int year;
};
回答by pinkpanther
Is it possible to write an entire struct to a file
是否可以将整个结构写入文件
Your question is actually writing struct instances into file.
您的问题实际上是将 struct 实例写入文件。
- You can use
fwritefunction to achieve this. - You need to pass the reference in first argument.
sizeofeach object in the second argument- Number of such objects to write in 3rd argument.
- File pointer in 4th argument.
- Don't forget to open the file in
binary mode. - You can read objects from file using fread.
Careful with endianness when you are writing/reading in little endian systems and reading/writing in big endian systems and viceversa. Read how-to-write-endian-agnostic-c-c-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); }
- 您可以使用
fwrite函数来实现这一点。 - 您需要在第一个参数中传递引用。
sizeof第二个参数中的每个对象- 要在第三个参数中写入的此类对象的数量。
- 第四个参数中的文件指针。
- 不要忘记在
binary mode. - 您可以使用 fread 从文件中读取对象。
在小端系统中写入/读取和在大端系统中读取/写入时要小心字节序,反之亦然。阅读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); }
You can read them in the same way....using fread
你可以用同样的方式阅读它们......使用 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);

