我正在尝试在 c 中创建一个简单的脚本,该脚本能够识别(设备)的坏扇区以用于教育目的。在我的示例中,我使用具有只读模式的 HD。背后的想法很简单,但可能太简单了,我会知道这是否正确,并最终了解实现我目标的任何其他方式。
让我们看一下我的代码:
#include<stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char ** argcv){
size_t size_block = 512;
int fd = open("/dev/disk2",O_RDONLY);
ssize_t bytes_read = 1;
char *buff = malloc(size_block * sizeof(char));
if (buff == NULL){
exit(EXIT_FAILURE);
}
while (bytes_read > 0){
bytes_read = read(fd,buff,size_block);
int position = lseek(fd, 0, SEEK_CUR);
if (bytes_read == -1){
perror("main");
}
//printf("%s",buff); //prints the content of what I read
if (bytes_read < size_block){
printf("the block at %p address is probably damaged",&position);
}
}
free(buff);
close(fd);
return 0;
}
所以我尝试通过每次寻找 512 字节的文件指针来读取我的 HD 扇区。这是第一个问题:由于首选的 I/O 块大小是 2048 字节(使用 sys/stat.h 的 stat 检索的信息),每次 512 字节而不是 2048 字节是否正确查找?另外,为了检查一个扇区是否坏,我用来比较(bytes_read < size_block)
,因为我假设如果我无法读取一个扇区的全部字节,它可能会被损坏。但是,如果我到达“文件的末尾”并且使用这种方法它不是 512 的倍数,我将得到该扇区无论如何都已损坏,如果它不是。我写的真的有用吗?否则,我该怎么做这个检查?