我正在开发一个项目,试图在文件系统(例如ext2)中搜索特定字节(例如0xAB)。我能够使用
更新:以下程序可以编译和运行,但我仍有几个问题:
1)对于大文件,它无法正确显示文件大小(对于1GB闪存驱动器显示正确大小,但对于32GB不是)*。
2)它没有正确地搜索映射**。
*使用
**这是搜索的正确方式吗?
感谢您的帮助。
malloc()
、realloc()
和memchr()
找到所需内容,但速度较慢,因此我正在考虑使用mmap()
。我的目标是找到特定字节,然后将它们复制到一个结构体中,所以我有两个问题:(1)使用mmap()
是否是最佳策略?(2)为什么下面的代码不起作用(我收到了EINVAL错误)?更新:以下程序可以编译和运行,但我仍有几个问题:
1)对于大文件,它无法正确显示文件大小(对于1GB闪存驱动器显示正确大小,但对于32GB不是)*。
2)它没有正确地搜索映射**。
*使用
stat64()
获取正确大小的方法是否可行?如果是,请问我该如何将其添加到Makefile中?我没有经验处理Makefile,不知道该如何添加。
**这是搜索的正确方式吗?
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
int main(int argc, char **argv) {
int fd = open("/dev/sdb1", O_RDONLY);
if(fd < 0) {
printf("Error %s\n", strerror(errno));
return -1;
}
const char * map;
off64_t size;
size = lseek64(fd, 0, SEEK_END);
printf("file size: %llu\n", size);
lseek64(fd, 0, SEEK_SET);
map = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) { handle_error("mmap error"); }
printf("Searching for magic numbers...\n");
for (i=0; i < size; i++) {
if(map[i] == 0X53 && map[i + 1] == 0XEF) {
if ((map[i-32] == 0X00 && map[i-31] == 0X00) ||
(map[i-32] == 0X01 && map[i-31] == 0X00) ||
(map[i-32] == 0X02 && map[i-31] == 0X00)) {
if(j <= 5) {
printf("superblock %d found\n", j);
++j;
} else break;
int q;
for(q=0; q<j; q++) {
printf("SUPERBLOCK[%d]: %d\n", q+1, sb_pos[q]);
}
fclose(fd);
munmap(map, size);
return 0;
}
感谢您的帮助。
size
)的长度。 - Sharkmalloc()
和realloc()
分配 X 字节,直到整个文件系统被搜索? - user2341909malloc()
和realloc()
可能会因与mmap()
相同的原因而失败。只需确保您对齐得很好即可。 - Shark