从.bin文件读取1024位数据并存储到数组的实现方法咨询
从.bin文件读取1024位数据并存储到数组的实现方法咨询
看起来你已经用FatFS框架搭好基础啦,我来帮你补全逻辑,实现每次读取128个8位数据(也就是1024bit)并存储到XW数组的每个索引中~
首先得理清楚数据对应关系:你的.bin文件总共有65536个8位数据(也就是65536字节),每次读128字节(1024bit),刚好要读512次,完美对应XW[512]的每个位置。不过这里有个小细节要注意:你定义的int XW[512]每个元素默认是4字节(32bit),根本存不下128个8位数据(128字节),所以得先调整XW的类型,下面给你两种常见的实现方案:
方案一:用二维数组直接存储(最直观)
这种方式每个XW[i]就是一个128字节的缓冲区,直接存每次读取的128个8位数据,代码补全后是这样的:
#include "ff.h" // 引入FatFS头文件 #include <stdio.h> #include <stdint.h> // 调整XW为二维数组,每个索引对应128个8位数据(1024bit) uint8_t XW[512][128] = {0}; int main(void) { FRESULT Res; FIL fil; UINT bytes_read; int i; // 打开文件 Res = f_open(&fil, "./xw_8bit.bin", FA_OPEN_EXISTING | FA_READ); if (Res != FR_OK) { printf("xw_8bit.bin open error, code: %d\n", Res); return -1; } // 定位到文件开头(其实打开文件后默认就在开头,这步可以省略,但加上更稳妥) Res = f_lseek(&fil, 0); if (Res != FR_OK) { printf("xw_8bit.bin seek error, code: %d\n", Res); f_close(&fil); // 出错记得关文件! return -1; } // 循环读取512次,每次128字节 for (i = 0; i < 512; i++) { Res = f_read(&fil, XW[i], 128, &bytes_read); // 检查读取结果:返回值正常,且实际读取字节数符合预期 if (Res != FR_OK || bytes_read != 128) { printf("Read failed at index %d, actual bytes read: %u\n", i, bytes_read); f_close(&fil); return -1; } } // 读取完成,关闭文件 f_close(&fil); printf("All data read successfully!\n"); return 0; }
方案二:用自定义结构体存储1024位数据
如果你希望XW的每个元素是一个“1024位整数”的抽象类型,可以自定义一个结构体来模拟,这样代码语义更清晰:
#include "ff.h" #include <stdio.h> #include <stdint.h> // 自定义1024位整数类型,用16个64位整数拼接而成(16*64=1024bit) typedef struct { uint64_t parts[16]; } uint1024_t; uint1024_t XW[512] = {0}; int main(void) { FRESULT Res; FIL fil; UINT bytes_read; int i; Res = f_open(&fil, "./xw_8bit.bin", FA_OPEN_EXISTING | FA_READ); if (Res != FR_OK) { printf("xw_8bit.bin open error, code: %d\n", Res); return -1; } for (i = 0; i < 512; i++) { // 直接把128字节的数据读到结构体的内存空间中 Res = f_read(&fil, &XW[i], 128, &bytes_read); if (Res != FR_OK || bytes_read != 128) { printf("Read failed at index %d, actual bytes read: %u\n", i, bytes_read); f_close(&fil); return -1; } } f_close(&fil); printf("All data read successfully!\n"); return 0; }
几个必看的小提醒
- 一定要关闭文件:不管读取成功还是失败,操作完文件后都要调用
f_close(&fil),否则会造成文件系统资源泄漏,甚至影响后续的文件操作。 - 校验读取结果:每次读取后不仅要检查
FRESULT返回值,还要看实际读取的字节数bytes_read,如果和预期的128不一致,说明文件可能不完整、损坏,或者读取过程中出了问题,必须及时处理。 - 字节序问题:如果你的数据有特定的字节序要求(比如大端/小端),读取后可能需要调整字节顺序,否则直接存储的是文件的原始字节序。
备注:内容来源于stack exchange,提问作者yui
相关产品推荐
相关产品推荐

