- add testcase for grep bug (http://busybox.net/bugs/view.php?id=887)
[oweals/busybox.git] / libbb / print_file.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include "libbb.h"
14
15 void bb_xprint_and_close_file(FILE *file)
16 {
17         bb_xfflush_stdout();
18         /* Note: Do not use STDOUT_FILENO here, as this is a lib routine
19          *       and the calling code may have reassigned stdout. */
20         if (bb_copyfd_eof(fileno(file), STDOUT_FILENO) == -1) {
21                 /* bb_copyfd outputs any needed messages, so just die. */
22                 exit(bb_default_error_retval);
23         }
24         /* Note: Since we're reading, don't bother checking the return value
25          *       of fclose().  The only possible failure is EINTR which
26          *       should already have been taken care of. */
27         fclose(file);
28 }
29
30 /* Returns:
31  *    0      if successful
32  *   -1      if 'filename' does not exist or is a directory
33  *  exits with default error code if an error occurs
34  */
35
36 int bb_xprint_file_by_name(const char *filename)
37 {
38         FILE *f;
39
40 #if 0
41         /* This check shouldn't be necessary for linux, but is left
42         * here disabled just in case. */
43         struct stat statBuf;
44
45         if(is_directory(filename, TRUE, &statBuf)) {
46                 bb_error_msg("%s: Is directory", filename);
47         } else
48 #endif
49         if ((f = bb_wfopen(filename, "r")) != NULL) {
50                 bb_xprint_and_close_file(f);
51                 return 0;
52         }
53
54         return -1;
55 }