I'm trying to create a simple script in c which is able to identify bad sectors of (a device) for educational purpose. In my example, I use an HD with read-only mode. The idea behind is simple, but maybe too simple and I would know if this is correct and eventually get known about any other way to reach my goal.
Let's take a look to my code:
#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;
}
So I try to read sectors of my HD with read syscalls by seeking the file pointer of 512 bytes every time. And that's the first question: since the preferred, I/O block size is 2048 byte (info retrieved with stat of sys/stat.h), is it correct seek every time of 512 bytes instead of 2048?
Also, to check if a sector is bad I use to compare (bytes_read < size_block)
because I assume that if I cannot read the totality of bytes of a sector, it could be damaged. But if I reach the end "of the file" and it isn't a multiple of 512 with this method I will get that the sector is damaged anyway also if it isn't. Is what I wrote really working? Otherwise, how can I do this check?