Pass file descriptor instead of file name

Passing a file descriptor to make_ext4fs_internal() is more flexible.
We can use tmpfile() to create a temporary file.
tmpfile() is better than other solutions because it unlinks the file
right after creating it, so closing fd effectively removes temp file.
Thus we don't have to worry about large temp files accidently left
on the filesystem in case of the program crash.

Change-Id: I44146704572c314e1d6cfca7ce918efa7fb92a7a
diff --git a/ext4_utils/make_ext4fs_main.c b/ext4_utils/make_ext4fs_main.c
index d616c6d..b83f57e 100644
--- a/ext4_utils/make_ext4fs_main.c
+++ b/ext4_utils/make_ext4fs_main.c
@@ -14,8 +14,9 @@
  * limitations under the License.
  */
 
-#include <unistd.h>
+#include <fcntl.h>
 #include <libgen.h>
+#include <unistd.h>
 
 #if defined(__linux__)
 #include <linux/fs.h>
@@ -49,6 +50,8 @@
         int crc = 0;
         int wipe = 0;
         int init_itabs = 0;
+        int fd;
+        int exitcode;
 
         while ((opt = getopt(argc, argv, "l:j:b:g:i:I:L:a:fwzJsct")) != -1) {
                 switch (opt) {
@@ -139,6 +142,19 @@
                 exit(EXIT_FAILURE);
         }
 
-        return make_ext4fs_internal(filename, directory, mountpoint, android, gzip,
+        if (strcmp(filename, "-")) {
+                fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
+                if (fd < 0) {
+                        error_errno("open");
+                        return EXIT_FAILURE;
+                }
+        } else {
+                fd = STDOUT_FILENO;
+        }
+
+        exitcode = make_ext4fs_internal(fd, directory, mountpoint, android, gzip,
                        sparse, crc, wipe, init_itabs);
+        close(fd);
+
+        return exitcode;
 }