From 5d34d8c327db3e471a578552ec50c6fb1840a6fb Mon Sep 17 00:00:00 2001 From: Jim Meyering Date: Sat, 3 Mar 2001 19:12:23 +0000 Subject: (xfopen): Set have_read_stdin to 1 only if file is "-". Use fopen_safer, not fopen, to avoid subtle bugs when fopen returns stdin, stdout, or stderr. (xfclose): stdout is no longer a special case. (main): Close output file, don't just flush it; there might be an error on the close. --- src/sort.c | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/sort.c b/src/sort.c index d6b46f5df..46744348f 100644 --- a/src/sort.c +++ b/src/sort.c @@ -35,6 +35,7 @@ #include "human.h" #include "memcoll.h" #include "physmem.h" +#include "stdio-safer.h" #include "xalloc.h" #include "xstrtol.h" @@ -409,11 +410,12 @@ xfopen (const char *file, const char *how) if (STREQ (file, "-")) { + have_read_stdin = 1; fp = stdin; } else { - if ((fp = fopen (file, how)) == NULL) + if ((fp = fopen_safer (file, how)) == NULL) { error (0, errno, "%s", file); cleanup (); @@ -421,8 +423,6 @@ xfopen (const char *file, const char *how) } } - if (fp == stdin) - have_read_stdin = 1; return fp; } @@ -435,15 +435,6 @@ xfclose (FILE *fp) if (feof (fp)) clearerr (fp); } - else if (fp == stdout) - { - if (fflush (fp) != 0) - { - error (0, errno, _("flushing file")); - cleanup (); - exit (SORT_FAILURE); - } - } else { if (fclose (fp) != 0) @@ -2520,12 +2511,7 @@ but lacks following character offset")); sort (files, nfiles, ofp, outfile); cleanup (); - /* If we wait for the implicit flush on exit, and the parent process - has closed stdout (e.g., exec >&- in a shell), then the output file - winds up empty. I don't understand why. This is under SunOS, - Solaris, Ultrix, and Irix. This premature fflush makes the output - reappear. --karl@cs.umb.edu */ - if (fflush (ofp) < 0) + if (fclose (ofp) != 0) error (SORT_FAILURE, errno, _("%s: write error"), outfile); if (have_read_stdin && fclose (stdin) == EOF) -- cgit v1.2.3-70-g09d2