Thomas Martitz | 249bba0 | 2011-12-24 11:56:46 +0000 | [diff] [blame] | 1 | /*************************************************************************** |
| 2 | * __________ __ ___. |
| 3 | * Open \______ \ ____ ____ | | _\_ |__ _______ ___ |
| 4 | * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / |
| 5 | * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < |
| 6 | * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ |
| 7 | * \/ \/ \/ \/ \/ |
| 8 | * $Id$ |
| 9 | * |
| 10 | * Copyright (C) 2011 Thomas Martitz |
| 11 | * |
| 12 | * This program is free software; you can redistribute it and/or |
| 13 | * modify it under the terms of the GNU General Public License |
| 14 | * as published by the Free Software Foundation; either version 2 |
| 15 | * of the License, or (at your option) any later version. |
| 16 | * |
| 17 | * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY |
| 18 | * KIND, either express or implied. |
| 19 | * |
| 20 | ****************************************************************************/ |
| 21 | |
| 22 | #include <unistd.h> |
| 23 | #include <sys/types.h> |
| 24 | #include <sys/stat.h> |
| 25 | #include <fcntl.h> |
| 26 | #include <stdio.h> |
| 27 | #include <stdlib.h> |
| 28 | #include <stdarg.h> |
| 29 | |
| 30 | /* A simple replacement program for ( |
| 31 | * dd if=$file1 of=$file2 bs=1 skip=$offset count=$size |
| 32 | * |
| 33 | * Written because byte-size operations with dd are unbearably slow. |
| 34 | */ |
| 35 | |
| 36 | void usage(void) |
| 37 | { |
| 38 | fprintf(stderr, "Usage: extract_section <romfile> <outfile> <offset> <byte count>\n"); |
| 39 | exit(1); |
| 40 | } |
| 41 | |
| 42 | void die(const char* fmt, ...) |
| 43 | { |
| 44 | va_list ap; |
| 45 | va_start(ap, fmt); |
| 46 | vfprintf(stderr, fmt, ap); |
| 47 | va_end(ap); |
| 48 | exit(1); |
| 49 | } |
| 50 | |
| 51 | int main(int argc, const char* argv[]) |
| 52 | { |
| 53 | if (argc != 5) |
| 54 | usage(); |
| 55 | |
| 56 | int ifd, ofd; |
| 57 | ssize_t size = atol(argv[4]); |
| 58 | long skip = atol(argv[3]); |
| 59 | |
| 60 | if (!size) |
| 61 | die("invalid byte count\n"); |
| 62 | |
| 63 | ifd = open(argv[1], O_RDONLY); |
| 64 | if (ifd < 0) |
| 65 | die("Could not open %s for reading!\n", argv[1]); |
| 66 | |
| 67 | ofd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0666); |
| 68 | if (ofd < 0) |
| 69 | die("Could not create %s\n", argv[2]); |
| 70 | |
| 71 | void *buf = malloc(size); |
| 72 | if (!buf) die("OOM\n"); |
| 73 | |
| 74 | lseek(ifd, skip, SEEK_SET); |
| 75 | lseek(ofd, 0, SEEK_SET); |
| 76 | if (read(ifd, buf, size) != size) |
| 77 | die("Read failed\n"); |
| 78 | if (write(ofd, buf, size) != size) |
| 79 | die("write failed\n"); |
| 80 | |
| 81 | close(ifd); |
| 82 | close(ofd); |
| 83 | |
| 84 | exit(EXIT_SUCCESS); |
| 85 | } |