将struct保存到文件
我想将多维数组保存到文件中。 结构例如:
struct StructSub { unsigned short id; }; struct MyStruct { struct StructSub sub[3]; }; // Use the struct struct MyStruct main; int i = 0; while (i < 3) { main.sub[i].id = i; i++; }
对于此示例,我想将数据保存为此格式的文件(普通文本):
MyStruct main { StructSub sub[0] { id = 0; } StructSub sub[1] { id = 1; } StructSub sub[2] { id = 2; } }
最简单的方法是什么?
我猜这样的事情更像是你想要的。 它并不像它可能的那样简洁,但它非常简单,可以很容易地扩展到适应其他结构。
void WriteIndent(FILE* file, int indent) { int i = 0; while (i < indent) { fprintf(file, "\t"); ++i; } } void WriteStructSub(FILE* file, StructSub* s, char* id, int indent) { WriteIndent(file, indent); fprintf(file, "StructSub %s {\n", id); WriteIndent(file, indent + 1); fprintf(file, "id = %i;\n", s->id); WriteIndent(file, indent); fprintf(file, "}\n"); } void WriteMyStruct(FILE* file, MyStruct* s, char* id, int indent) { WriteIndent(file, indent); fprintf(file, "MyStruct %s {\n", id); int i = 0; while (i < 3) { char name[7]; sprintf(name, "sub[%i]", i); WriteStructSub(file, &s->sub[i], name, indent + 1); ++i; } WriteIndent(file, indent); fprintf(file, "}\n"); } int main(int argc, char** argv) { MyStruct s; int i = 0; while (i < 3) { s.sub[i].id = i; ++i; } FILE* output = fopen("data.out", "w"); WriteMyStruct(output, &s, "main", 0); fclose(output); }
请记住,将原始结构保存到这样的文件根本不可移植。 编译器可能会向struct添加填充(更改sizeof(your_struct)),endianness可能会有所不同等等。但是,如果这是无关紧要的,那么fwrite()工作正常。
请记住,如果您的结构包含任何指针,您希望编写指针指向的数据,而不是指针本身的值。
试试这个
struct StructSub { unsigned short id; }; struct MyStruct { struct StructSub sub[10]; }; // Use the struct struct MyStruct main; int i = 0; while (i < 10) { main.sub[i].id = i; }
写入文件
FILE* output; output = fopen("Data.dat", "wb"); fwrite(&main, sizeof(main), 1, output); fclose(output);
读取文件
struct Data data; FILE* input; input = fopen("Data.dat", "rb"); fread(&main, sizeof(main), 1, input); // you got the data from the file! fclose(input);
这些链接支持以上代码的全部内容 - http://c-faq.com/struct/io.html
fwrite(&somestruct, sizeof somestruct, 1, fp);
您可以使用可用的序列化库来执行此操作。
如果你可以使用C ++,那么就有Boost :: Serialization库。 您可能还想结帐:
- s11n图书馆。
- 这个答案 。
- Tpl库。
你可以使用基本的文件,只要确保你写二进制 。
FILE * pFile; pFile = fopen( "structs.bin","wb" ); if ( pFile!=NULL ) { frwite( main, 1, sizeof(struct MyStruct), pFile ); fclose (pFile); }
如果你这样做的话,它不是最容易移植的平台,因为需要考虑字节序。
除了main
的对象的名称,这可能会导致任何奇怪的问题:只是暴力 – 它没有更好的方法:)
/* pseudo code */ write struct header foreach element write element header write element value(s) write element footer endfor write struct footer