about summary refs log tree commit diff
path: root/stdio-common/tst-freopen3-main.c
blob: 5107e1f98e189e4bfbbbb806c7dc08121fd6485f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* Test freopen failure.
   Copyright (C) 2024 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <https://www.gnu.org/licenses/>.  */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#include <support/check.h>
#include <support/descriptors.h>
#include <support/file_contents.h>
#include <support/support.h>
#include <support/temp_file.h>
#include <support/test-driver.h>
#include <support/xstdio.h>

#define START_TEST(DESC)			\
  do						\
    {						\
      fds = support_descriptors_list ();	\
      verbose_printf (DESC);			\
    }						\
  while (0)

#define END_TEST				\
  do						\
    {						\
      support_descriptors_check (fds);		\
      support_descriptors_free (fds);		\
    }						\
  while (0)

int
do_test (void)
{
  struct support_descriptors *fds;
  char *temp_dir = support_create_temp_directory ("tst-freopen3");
  char *file1 = xasprintf ("%s/file1", temp_dir);
  support_write_file_string (file1, "file1");
  add_temp_file (file1);
  char *file2 = xasprintf ("%s/file2", temp_dir);
  support_write_file_string (file2, "file2");
  add_temp_file (file2);
  char *file_nodir = xasprintf ("%s/nodir/file", temp_dir);
  FILE *fp;
  int ret;
  int fd;

  START_TEST ("Testing w -> wx (file exists)\n");
  fp = xfopen (file1, "w");
  fp = FREOPEN (file2, "wx", fp);
  TEST_VERIFY (fp == NULL);
  END_TEST;

  /* Test old file is closed even when opening the new file fails.  */

  START_TEST ("testing r -> r (opening new file fails)\n");
  fp = xfopen (file1, "r");
  fd = fileno (fp);
  fp = FREOPEN (file_nodir, "r", fp);
  TEST_VERIFY (fp == NULL);
  errno = 0;
  ret = fcntl (fd, F_GETFL);
  TEST_COMPARE (ret, -1);
  TEST_COMPARE (errno, EBADF);
  END_TEST;

  free (temp_dir);
  free (file1);
  free (file2);
  free (file_nodir);
  return 0;
}

#include <support/test-driver.c>