/* * read_data v1.3 (c) 1998,2004 by van Hauser / THC * http://www.thc.org * * reads data from a blockdevice into a file. */ #include #include #include #include #include #include #include #define MAX_SIZE 100000 /* max bytes to read */ int main (int argc, char *argv[]) { char dev[100]; unsigned long bytes, reat; off_t start; struct stat st; int f; char buf[MAX_SIZE]; char filename[50]; if (argc!=4) { printf("Syntax: %s blockdevice start_address no_of_bytes\n",argv[0]); printf("Output is saved to start_address_no_of_bytes\n"); exit(1); } strncpy(dev, argv[1], sizeof(dev)-1); if (sizeof(start) < 8) start = atol(argv[2]); else start = strtoll(argv[2], (char **)NULL, 10); bytes = atol(argv[3]); if ((bytes < 1) || (bytes > MAX_SIZE)) { printf("Error: number of bytes to read must be between 1 and %d\n", MAX_SIZE); exit (1); } if (lstat(dev, &st) != 0) { perror("Can't access blockdevice"); exit(1); } if ((st.st_mode & S_IFBLK) != S_IFBLK) { printf("Warning: %s is not a block device\n", dev); } sync(); if ((f = open(dev, O_RDONLY)) < 0) { perror("Can't open blockdevice for reading"); exit(1); } if (lseek(f, start, SEEK_SET) < 0) { if (sizeof(start) < 8) printf("Can't seek to offset %lu\n", (unsigned long) start); else printf("Can't seek to offset %llu\n", (unsigned long long) start); exit(1); } reat = read(f, buf, bytes); if (reat <= 0) { printf("Couldn't read data from device\n"); exit(1); } if (reat != bytes) { printf("Warning: I could only read %lu bytes\n", reat); } close(f); if (sizeof(start) < 8) sprintf(filename, "%lu.%lu", (unsigned long) start, reat); else sprintf(filename, "%llu.%lu", (unsigned long long) start, reat); if ((f = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0600)) < 0) { perror("Could not create outputfile"); exit(1); } if (write(f, buf, reat) != reat) { printf("Could not write all data to file %s\n", filename); exit(1); } close(f); printf("Output successfully written into the file %s\n", filename); exit(0); }