1 /* vi: set sw=4 ts=4: */
3 * Mini dd implementation for busybox
6 * Copyright (C) 2000,2001 Matt Kraai
8 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
11 #include <sys/types.h>
21 static const struct suffix_mult dd_suffixes[] = {
34 int dd_main(int argc, char **argv)
45 int sync_flag = FALSE;
47 int trunc_flag = TRUE;
52 const char *infile = NULL;
53 const char *outfile = NULL;
56 for (i = 1; i < argc; i++) {
57 if (strncmp("bs=", argv[i], 3) == 0)
58 bs = bb_xparse_number(argv[i]+3, dd_suffixes);
59 else if (strncmp("count=", argv[i], 6) == 0)
60 count = bb_xparse_number(argv[i]+6, dd_suffixes);
61 else if (strncmp("seek=", argv[i], 5) == 0)
62 seek = bb_xparse_number(argv[i]+5, dd_suffixes);
63 else if (strncmp("skip=", argv[i], 5) == 0)
64 skip = bb_xparse_number(argv[i]+5, dd_suffixes);
65 else if (strncmp("if=", argv[i], 3) == 0)
67 else if (strncmp("of=", argv[i], 3) == 0)
69 else if (strncmp("conv=", argv[i], 5) == 0) {
72 if (strncmp("notrunc", buf, 7) == 0) {
75 } else if (strncmp("sync", buf, 4) == 0) {
78 } else if (strncmp("noerror", buf, 7) == 0) {
82 bb_error_msg_and_die("invalid conversion `%s'", argv[i]+5);
96 ifd = bb_xopen(infile, O_RDONLY);
99 infile = bb_msg_standard_input;
102 if (outfile != NULL) {
103 oflag = O_WRONLY | O_CREAT;
105 if (!seek && trunc_flag) {
109 ofd = bb_xopen3(outfile, oflag, 0666);
111 if (seek && trunc_flag) {
112 if (ftruncate(ofd, seek * bs) < 0) {
115 if (fstat (ofd, &st) < 0 || S_ISREG (st.st_mode) ||
116 S_ISDIR (st.st_mode)) {
117 bb_perror_msg_and_die("%s", outfile);
123 outfile = bb_msg_standard_output;
127 if (lseek(ifd, skip * bs, SEEK_CUR) < 0) {
128 bb_perror_msg_and_die("%s", infile);
133 if (lseek(ofd, seek * bs, SEEK_CUR) < 0) {
134 bb_perror_msg_and_die("%s", outfile);
138 while (in_full + in_part != count) {
140 /* Pre-zero the buffer when doing the noerror thing */
141 memset(buf, '\0', bs);
143 n = safe_read(ifd, buf, bs);
147 bb_perror_msg("%s", infile);
149 bb_perror_msg_and_die("%s", infile);
155 if ((size_t)n == bs) {
161 memset(buf + n, '\0', bs - n);
164 n = bb_full_write(ofd, buf, n);
166 bb_perror_msg_and_die("%s", outfile);
168 if ((size_t)n == bs) {
175 if (close (ifd) < 0) {
176 bb_perror_msg_and_die("%s", infile);
179 if (close (ofd) < 0) {
180 bb_perror_msg_and_die("%s", outfile);
183 fprintf(stderr, "%ld+%ld records in\n%ld+%ld records out\n",
184 (long)in_full, (long)in_part,
185 (long)out_full, (long)out_part);