maint: update copyright
[gnulib.git] / tests / test-freopen.c
1 /* Test of opening a file stream.
2    Copyright (C) 2007-2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Bruno Haible <bruno@clisp.org>, 2007.  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22
23 #include "signature.h"
24 SIGNATURE_CHECK (freopen, FILE *, (char const *, char const *, FILE *));
25
26 #include <errno.h>
27 #include <unistd.h>
28
29 #include "macros.h"
30
31 int
32 main ()
33 {
34   const char *filename = "test-freopen.txt";
35
36   ASSERT (freopen ("/dev/null", "r", stdin) != NULL);
37
38 #if 0 /* freopen (NULL, ...) is unsupported on most platforms.  */
39   /* Test that freopen() sets errno if someone else closes the stream
40      fd behind the back of stdio.  */
41   {
42     FILE *fp = fopen (filename, "w+");
43     ASSERT (fp != NULL);
44     ASSERT (close (fileno (fp)) == 0);
45     errno = 0;
46     ASSERT (freopen (NULL, "r", fp) == NULL);
47     perror("freopen");
48     ASSERT (errno == EBADF);
49     fclose (fp);
50   }
51
52   /* Test that freopen() sets errno if the stream was constructed with
53      an invalid file descriptor.  */
54   {
55     FILE *fp = fdopen (-1, "w+");
56     if (fp != NULL)
57       {
58         errno = 0;
59         ASSERT (freopen (NULL, "r", fp) == NULL);
60         ASSERT (errno == EBADF);
61         fclose (fp);
62       }
63   }
64   {
65     FILE *fp;
66     close (99);
67     fp = fdopen (99, "w+");
68     if (fp != NULL)
69       {
70         errno = 0;
71         ASSERT (freopen (NULL, "r", fp) == NULL);
72         ASSERT (errno == EBADF);
73         fclose (fp);
74       }
75   }
76 #endif
77
78   /* Clean up.  */
79   unlink (filename);
80
81   return 0;
82 }