Credited Christophe Boyaniqu for interactive patch to rm.
[oweals/busybox.git] / dd.c
diff --git a/dd.c b/dd.c
index a0d2330ea6511d47f2c15f1bedc260299e93ed8b..1618dd102a81c50a8442691136ff169496c80936 100644 (file)
--- a/dd.c
+++ b/dd.c
  *
  */
 
-#include "busybox.h"
-
 #include <sys/types.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
 #include <fcntl.h>
+#include "busybox.h"
 
-static struct suffix_mult dd_suffixes[] = {
+
+static const struct suffix_mult dd_suffixes[] = {
        { "c", 1 },
        { "w", 2 },
        { "b", 512 },
@@ -41,7 +45,7 @@ static struct suffix_mult dd_suffixes[] = {
 
 int dd_main(int argc, char **argv)
 {
-       int i, ifd, ofd, sync = FALSE, trunc = TRUE;
+       int i, ifd, ofd, oflag, sync = FALSE, trunc = TRUE;
        size_t in_full = 0, in_part = 0, out_full = 0, out_part = 0;
        size_t bs = 512, count = -1;
        ssize_t n;
@@ -72,7 +76,7 @@ int dd_main(int argc, char **argv)
                                        sync = TRUE;
                                        buf += 4;
                                } else {
-                                       error_msg_and_die("invalid conversion `%s'\n", argv[i]+5);
+                                       error_msg_and_die("invalid conversion `%s'", argv[i]+5);
                                }
                                if (buf[0] == '\0')
                                        break;
@@ -80,7 +84,7 @@ int dd_main(int argc, char **argv)
                                        buf++;
                        }
                } else
-                       usage(dd_usage);
+                       show_usage();
        }
 
        buf = xmalloc(bs);
@@ -94,8 +98,19 @@ int dd_main(int argc, char **argv)
        }
 
        if (outfile != NULL) {
-               if ((ofd = open(outfile, O_WRONLY | O_CREAT, 0666)) < 0)
+               oflag = O_WRONLY | O_CREAT;
+
+               if (!seek && trunc)
+                       oflag |= O_TRUNC;
+
+               if ((ofd = open(outfile, oflag, 0666)) < 0)
                        perror_msg_and_die("%s", outfile);
+
+               if (seek && trunc) {
+                       if (ftruncate(ofd, seek * bs) < 0)
+                               perror_msg_and_die("%s", outfile);
+               }
+
                statusfp = stdout;
        } else {
                ofd = STDOUT_FILENO;
@@ -113,11 +128,6 @@ int dd_main(int argc, char **argv)
                        perror_msg_and_die("%s", outfile);
        }
 
-       if (trunc) {
-               if (ftruncate(ofd, seek * bs) < 0)
-                       perror_msg_and_die("%s", outfile);
-       }
-
        while (in_full + in_part != count) {
                n = safe_read(ifd, buf, bs);
                if (n < 0)