Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中的文件中存储和还原结构_C_File_Struct_Restore - Fatal编程技术网

在C中的文件中存储和还原结构

在C中的文件中存储和还原结构,c,file,struct,restore,C,File,Struct,Restore,我需要在一个文件中存储一个结构,然后将其读回并返回。 我会尝试这样将其写入文件: void lld_tpWriteCalibration(struct cal cal) { FIL fdst; /* file objects */ UINT bw; /* File write count */ /* Create destination file on the drive 0 */ wf_open(&fdst, "0:calibra

我需要在一个文件中存储一个结构,然后将其读回并返回。 我会尝试这样将其写入文件:

void lld_tpWriteCalibration(struct cal cal) {
    FIL fdst;      /* file objects */
   UINT bw;        /* File write count */

    /* Create destination file on the drive 0 */
    wf_open(&fdst, "0:calibration.txt", FA_CREATE_ALWAYS | FA_WRITE);
    wf_write(&fdst, cal, sizeof(cal), &bw);

    wf_close(&fdst);
}
这样行吗? 我如何读回它并从这个函数返回它

struct cal lld_tpReadCalibration(void) {

}
结构是:

   struct cal {
       float xm; 
       float ym; 
       float xn; 
       float yn; 
   };

感谢您的帮助。

您可以用存储结构的相同方式检索结构

read(&fdst, &cal, sizeof(cal));

但您必须小心,因为存在问题,您不可能在所有体系结构上都这样做。

如果您只尝试在写入文件时在同一类型的机器上读取该文件,您就可以使用该结构和写入/读取技术。这样编写的数据在不同类型的机器上不能可靠地移植。

因为mystic meg不在房间里-什么是
struct cal
?wf_open和wf_write不是标准的C函数,所以我不能说代码是否工作。但该代码看起来与标准的fopen/fwrite/fclose序列非常接近,因此它可能可以工作。reader函数将使用fread()的模拟值。然而,我不明白为什么有三个人对这个定义不明确的问题投了赞成票。这个函数确实与标准C函数兼容。但是,当我读回字节时,如何将其重新组装为结构?或者我只是把它读回一个缓冲区,然后返回缓冲区?那么你有没有试过wf_read或者它的名字?没有明显的原因说明为什么回读您写入文件的内容不起作用。任何问题都可能是由于数据不再有效。例如,在程序运行之间,重新读取指针可能感觉不到。但如果只是字符串、时间戳或类似的独立数据,那么将其读回应该没问题。在任何给定的平台上,您都可以安全地读写此类文件。您将无法自信地将这样写入的数据移动到不同类型的机器(不同的CPU)。