本文主要是介绍mtd分区应用操作sample之某分区读,然后保存文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用到的头文件
#include <mtd/mtd-user.h>
#include <mtd/mtd-abi.h>struct mtd_info_user
{__u8 type;__u32 flags;__u32 size; /* Total size of the MTD */ //该分区总大小__u32 erasesize; //擦除的块大小 __u32 writesize;__u32 oobsize; /* Amount of OOB data per block (e.g. 16) */__u64 padding; /* Old obsolete field; do not use */
};
//下面是某分区读,然后是保存文件的例子
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <mtd/mtd-user.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>#define FILE_NAME "read_raw_file"int main()
{int mtd_fd;struct mtd_info_user mtd_info;char *mtd_dev = "/dev/mtd1"; // 替换为你的MTD设备文件struct timeval tv1,tv2;uint8_t* buffer = NULL;FILE *fp = NULL;// 打开MTD设备mtd_fd = open(mtd_dev, O_RDONLY);if (mtd_fd < 0) {perror("Error opening MTD device");return EXIT_FAILURE;}if (!(fp = fopen(FILE_NAME, "wb"))) {perror("Error write file ");return EXIT_FAILURE;}// 获取MTD设备信息if (ioctl(mtd_fd, MEMGETINFO, &mtd_info)) {perror("Error getting MTD info");close(mtd_fd);return EXIT_FAILURE;}printf("MTD Device Info:\n");printf(" type: %llu\n", mtd_info.type); //识别是nor flash 还是 nand flash printf(" flags: %llu\n", mtd_info.flags);printf(" Size: %llu\n", mtd_info.size); // 分区的大小 printf(" Erase Size: %u\n", mtd_info.erasesize); // 擦除块大小printf(" Write Size: %u\n", mtd_info.writesize);printf(" oobsize Size: %u\n", mtd_info.oobsize);printf(" padding Size: %u\n", mtd_info.padding);// ... 打印其他MTD信息buffer = malloc(mtd_info.size);memset(buffer,0,mtd_info.size);gettimeofday(&tv1, NULL);// 读取数据if (pread(mtd_fd, buffer, mtd_info.size, 0) < 0){ // 从设备偏移0处读取perror("Error reading from MTD device");close(mtd_fd);return EXIT_FAILURE;}gettimeofday(&tv2, NULL);printf("millisecond: %ld\n",(tv2.tv_sec * 1000 + tv2.tv_usec / 1000) - ( tv1.tv_sec * 1000 + tv1.tv_usec / 1000));fwrite(buffer, 1, mtd_info.size, fp);fflush(fp);#if 0 // 打印读取的数据(仅示例,可能需要根据实际数据格式进行处理)printf("Data read from MTD device:\n");for (size_t i = 0; i < read_size; ++i) {printf("%02x ", buffer[i]);if ((i + 1) % 16 == 0) {printf("\n");}}
#endif if(fp) {fclose(fp);}free(buffer);// 关闭MTD设备close(mtd_fd);return EXIT_SUCCESS;
}
/mnt # ./mtd_test
MTD Device Info:type: 3flags: 3072Size: 9437184Erase Size: 65536Write Size: 1oobsize Size: 0padding Size: 0
millisecond: 411
写入测试
./flashcp -v read_raw_file /dev/mtd1
这篇关于mtd分区应用操作sample之某分区读,然后保存文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!