写作结构体在C文件 [英] Writing Structs to a file in c
本文介绍了写作结构体在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能对整个结构写入一个文件
例如:
结构日期{
焦天[80];
INT月;
INT年;
};
解决方案
是否有可能对整个结构写入一个文件
块引用>您的问题是实际编写结构实例到文件中。
- 您可以使用
FWRITE
函数来实现这一点。- 您需要传递的第一个参数参考。
的sizeof
第二个参数中的每个对象- 此类对象的数量在第三个参数写入。
- 在第四个参数文件指针。
- 请不要忘记
二进制模式
来打开该文件。- 您可以从文件中使用的fread读取对象。
小心使用,当你写/读小端系统和读/大端系统,反之亦然写字节顺序。读<一个href=\"http://stackoverflow.com/questions/13994674/how-to-write-endian-agnostic-c-c-$c$c\">how-to-write-endian-agnostic-c-c-$c$c
结构日期*对象=的malloc(sizeof的(结构日期));
的strcpy(对象 - &GT;的一天,好天);
对象 - &GT;当月= 6;
对象 - &GT;同期= 2013;
FILE *文件=的fopen(输出,世行);
如果(文件!= NULL){
FWRITE(对象的sizeof(结构日期),1,文件);
FCLOSE(文件);
}
您可以用同样的方式阅读....使用
FREAD
结构日期* = Object2的malloc的(sizeof的(结构日期));
FILE *文件=的fopen(输出,RB);
如果(文件!= NULL){
FREAD(Object2的,的sizeof(结构日期),1,文件);
FCLOSE(文件);
}
的printf(%s /%D /%d个\\ N,object2-&GT;的一天,object2-&GT;当月,object2-&GT;一年);Is it possible to write an entire struct to a file
example:
struct date { char day[80]; int month; int year; };
解决方案Is it possible to write an entire struct to a file
Your question is actually writing struct instances into file.
- You can use
fwrite
function to achieve this.- You need to pass the reference in first argument.
sizeof
each 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); }
You can read them in the same way....using
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);
这篇关于写作结构体在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文