用到的头文件
#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: 3
flags: 3072
Size: 9437184
Erase Size: 65536
Write Size: 1
oobsize Size: 0
padding Size: 0
millisecond: 411
写入测试
./flashcp -v read_raw_file /dev/mtd1