2011-02-27 51 views
0

我在写一个程序内的结构时遇到了一些问题。 背景;我正在用ARMv7芯片在C上开发代码。该系统有一个带FAT16文件系统的SD卡用于文件访问。 我正在使用FAT16文件读取和写入操作来完成文件输出/输入的任何工作。 目前我在main函数之前声明了一个全局结构体;使用ARM进行C编程 - 将结构输出并输入到文件

struct config_information 
{ 
    char *name; 

    //version 
    char *fwversion; 

    //IP address 
    char *ip; 
}; 

//Declare structs for config information 
struct config_information config; 
struct config_information loadedconfig; 

指针用于字符串使用。 例如,我使用& config.name将数据读入这些变量。我必须使用我写的函数来读取通过串口接收到的字符到另一个字符指针strcat到另一个,但这工作正常,我已验证用户输入的细节匹配录制的输入(有一个快速如果有人想知道,可以在终端窗口提示屏幕提示输入详细信息)。

然后我实现了提供的库函数来将结构保存到一个文件;

fat16_write_file(CONF_FILE,&config, READBUFSIZE); 

哪里CONF_FILE仅仅是要使用的文件的文件句柄,&配置是一个输出缓冲器和READBUFSIZE是缓冲区(定义为148的尺寸,对于我而言足够大,但以后我希望改变它计算要输出的结构的大小,然后计算文件大小以便能够正确读取它)。如果我不清楚,我已经添加了库提供的函数定义,并在末尾加入开头语句以供参考。

这很好用,文件中的输出是; 名称1.1 192.168.1.1 有很多空白。显然,我输入名称作为名称,1.1作为固件,IP是自我解释的。

天真地我以为我可以做相反的事情,将它读回到我声明的loadconfig结构体中;

fat16_read_file(CONF_FILE,&loadedconfig,READBUFSIZE); 

显然,这种没有工作的结构没有任何预先定义的尺寸就知道多少回读的希望。

所以,我怎样才能读取数据我已经保存回它来自同一个结构? 这个名字的大小可以是任意大小,并不是很大,但它不能被安全地预测。固件版本将永远只有#。#,IP明显在已定义的范围内。

感谢您提供正确方向的提示或指示。请询问您是否需要更多信息来了解范围。

仅供参考;

/** 
* \ingroup fat16_file 
* Reads data from a file. 
* 
* The data requested is read from the current file location. 
* 
* \param[in] fd The file handle of the file from which to read. 
* \param[out] buffer The buffer into which to write. 
* \param[in] buffer_len The amount of data to read. 
* \returns The number of bytes read, 0 on end of file, or -1 on failure. 
* \see fat16_write_file 
*/ 
int16_t fat16_read_file(struct fat16_file_struct* fd, uint8_t* buffer, uint16_t buffer_len) 

/** 
* \ingroup fat16_file 
* Writes data to a file. 
* 
* The data is written to the current file location. 
* 
* \param[in] fd The file handle of the file to which to write. 
* \param[in] buffer The buffer from which to read the data to be written. 
* \param[in] buffer_len The amount of data to write. 
* \returns The number of bytes written, 0 on disk full, or -1 on failure. 
* \see fat16_read_file 
*/ 
int16_t fat16_write_file(struct fat16_file_struct* fd, const uint8_t* buffer, uint16_t buffer_len) 

回答

2

如果您希望将结构写入文件然后重新读入,您不应该为其成员使用指针。你应该这样声明:

/* specify sizes according to your needs */ 
#define MAX_NAME_SIZE 16 
#define MAX_FWVERSION_SIZE 16 
#define MAX_IP_SIZE 16 

struct config_information 
{ 
    char name[MAX_NAME_SIZE]; 

    //version 
    char fwversion[MAX_FWVERSION_SIZE]; 

    //IP address 
    char ip[MAX_IP_SIZE]; 
}; 

// write it to a file 
fat16_write_file(CONF_FILE,&config, sizeof(config_information)); 

// read it from a file 
fat16_read_file(CONF_FILE,&loadedconfig, sizeof(config_information)); 
+0

感谢您的回答。我尝试了类似于上述的东西,但没有多少运气。我只是尝试了上面发布的内容(将sizeof调用更改为sizeof(struct config_information)),并且它仍然没有读取任何内容到loadedconfig结构中。 更改后,仍然像以前一样正确保存数据(由于最大大小的定义,其大小不同)。 – Draineh

+0

对,事实证明,每次SD卡都受到文件描述符可以更改的同步操作。在我上面的例子中,我分配文件描述符,写入文件,然后尝试读取它。 我所需要做的就是在再次读取操作之前打开文件。 – Draineh

相关问题