将结构保存到文件
我想将多维数组保存到文件中。 A为例结构:将结构保存到文件
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);
}
你可以使用基本的文件,只要确保你写在二进制。
FILE * pFile;
pFile = fopen("structs.bin","wb");
if (pFile!=NULL) {
frwite(main, 1, sizeof(struct MyStruct), pFile);
fclose (pFile);
}
如果你这样做,虽然这种方式,它不是最便携的平台,因为是字节顺序考虑。
+1提到endian问题。 – 2010-09-26 15:48:01
试试这个
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' **程序中建议称为'main'的结构实例?! – 2010-09-26 11:08:00
雅,因为他想保存为文件,它的工作原理 – 2010-09-26 11:18:13
这绝对不会输出在问题要求的文件格式。 – 2010-09-26 11:22:10
请记住,将原始结构体保存到像这样的文件根本不是可移植的。编译器可能会将填充添加到结构中(更改sizeof(your_struct)),endianness可能会不同,等等。但是,如果这不是问题,那么fwrite()可以正常工作。
请记住,如果您的结构体包含任何指针,您希望写入指针指向的数据,而不是指针本身的值。
从对象的名称
除了能main
,这可能会导致你的任何数量的奇怪的问题:刚蛮力吧 - 有没有更好的办法:)
/* pseudo code */
write struct header
foreach element
write element header
write element value(s)
write element footer
endfor
write struct footer
谢谢,这有帮助! – Midas 2010-09-27 17:27:39