ddscratch/main.c

148 lines
3.1 KiB
C

#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
char devpath[FILENAME_MAX];
char targetpath[FILENAME_MAX];
int firstSector = -1;
long offset = -1;
int cntSectors = -1;
int sectSize = 4096;
void printUsage();
int scratch(int dev, int image,int sector,int size);
int main(int argc, char **argv) {
int ch;
while ((ch = getopt(argc, argv, "o:c:s:h")) != -1){
switch (ch){
case 'o':
offset = strtol(optarg, NULL, 0);
break;
case 'b':
offset = strtol(optarg, NULL, 0);
break;
case 'c':
cntSectors = strtol(optarg, NULL, 0);
break;
case 's':
sectSize = strtol(optarg, NULL, 0);
case 'h':
printUsage();
return 0;
}
}
if (optind != (argc-2)){
printUsage();
return -1;
}
strncpy(devpath, argv[optind], sizeof(devpath));
strncpy(targetpath, argv[optind+1], sizeof(targetpath));
if ((offset != -1) && (firstSector != -1)){
printUsage();
printf("only first sector OR offset may be given!\n");
}
if (offset != -1)
firstSector = (int)(offset / sectSize);
if (firstSector == -1)
firstSector = 0;
int dev = open(devpath, O_RDONLY);
if (dev == -1){
printf("could not open device %s\n", devpath);
return -2;
}
long devsize = lseek(dev, 0, SEEK_END);
if (cntSectors == -1)
cntSectors = (int)(devsize / sectSize);
int target = open(devpath, O_RDONLY);
if (target == -1){
printf("could not open target image %s\n", targetpath);
close(dev);
return -3;
}
printf("target (image file): %s\n", targetpath);
printf("device: %s\n", devpath);
printf("sector size: %i\n", sectSize);
printf("offset: 0x%08lx\n", ((long)firstSector * sectSize));
printf("first sector: %i\n", firstSector);
printf("sectors: %i\n", cntSectors);
for (int n=0;n<cntSectors;n++){
scratch(dev, target, firstSector + n, sectSize);
}
close(target);
close(dev);
return 0;
}
int scratch(int dev, int image,int sector,int size){
char p[size];
long offset = (long)sector * size;
for (int n = 0; n < 16; n++){
printf("\r#%08i 0x%08lX %i", sector, offset, n);
if (lseek(dev, offset, SEEK_SET) != offset){
printf("\ncould not seek (dev).\n");
return -1;
}
if (lseek(image, offset, SEEK_SET) != offset){
printf("\ncould not seek (image).\n");
return -1;
}
int nread = read(dev, p, size);
if (nread == -1){
continue;
} else {
if (nread < size) {
printf("\nshort read!\n");
}
write(image, p, nread);
return size;
}
}
}
void printUsage(){
printf("usage: ddscratch ( [-b <firstsector> ] | [-o <offset>] ) [-c <sectorcount>] [-s <sectorsize>] <path> <target>\n");
}