[Toybox] [PATCH] sort -o: fix behavior when output file is one of the input files.

enh enh at google.com
Mon Feb 4 17:47:54 PST 2019


Bug: http://b/123902291
---
 tests/sort.test   | 2 ++
 toys/posix/sort.c | 7 ++++---
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/tests/sort.test b/tests/sort.test
index c71012f0..a40d1b0f 100755
--- a/tests/sort.test
+++ b/tests/sort.test
@@ -13,6 +13,8 @@ testing "stdin" "sort" "a\nb\nc\n" "" "b\na\nc\n"
 testing "numeric" "sort -n input" "1\n3\n010\n" "3\n1\n010\n" ""
 testing "reverse" "sort -r input" "wook\nwalrus\npoint\npabst\naargh\n" \
  "point\nwook\npabst\naargh\nwalrus\n" ""
+testing "sort -o" "sort input -o output && cat output" "a\nb\nc\n"
"c\na\nb\n" ""
+testing "sort -o same" "sort input -o input && cat input" "a\nb\nc\n"
"c\na\nb\n" ""

 # Longish chunk of data re-used by the next few tests.  The expected output
 # varies, but the input (this) is the same.
diff --git a/toys/posix/sort.c b/toys/posix/sort.c
index 6f5467e1..9433aef2 100644
--- a/toys/posix/sort.c
+++ b/toys/posix/sort.c
@@ -304,9 +304,6 @@ void sort_main(void)
 {
   int idx, fd = 1;

-  // Open output file if necessary.
-  if (TT.o) fd = xcreate(TT.o, O_CREAT|O_TRUNC|O_WRONLY, 0666);
-
   // Parse -k sort keys.
   if (TT.k) {
     struct arg_list *arg;
@@ -384,6 +381,10 @@ void sort_main(void)
     if (TT.linecount) TT.linecount = jdx+1;
   }

+  // Open output file if necessary. We can't do this until we've finished
+  // reading in case the output file is one of the input files.
+  if (TT.o) fd = xcreate(TT.o, O_CREAT|O_TRUNC|O_WRONLY, 0666);
+
   // Output result
   for (idx = 0; idx<TT.linecount; idx++) {
     char *s = TT.lines[idx];
-- 
2.20.1.611.gfbb209baf1-goog
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 0001-sort-o-fix-behavior-when-output-file-is-one-of-the-i.patch
Type: text/x-patch
Size: 1832 bytes
Desc: not available
URL: <http://lists.landley.net/pipermail/toybox-landley.net/attachments/20190204/d6a7b9cb/attachment.bin>


More information about the Toybox mailing list