1 /* Test of fclose module.
2 Copyright (C) 2011-2024 Free Software Foundation, Inc.
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, or (at your option)
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Eric Blake. */
23 #include "signature.h"
24 SIGNATURE_CHECK (fclose
, int, (FILE *));
34 #define BASE "test-fclose.t"
37 main (int argc
, char **argv
)
39 const char buf
[] = "hello world";
44 /* Prepare a seekable file. */
45 fd
= open (BASE
, O_RDWR
| O_CREAT
| O_TRUNC
, 0600);
47 ASSERT (write (fd
, buf
, sizeof buf
) == sizeof buf
);
48 ASSERT (lseek (fd
, 1, SEEK_SET
) == 1);
50 /* Create an output stream visiting the file; when it is closed, all
51 other file descriptors visiting the file must see the new file
55 f
= fdopen (fd2
, "w");
57 ASSERT (fputc (buf
[1], f
) == buf
[1]);
58 ASSERT (fclose (f
) == 0);
60 ASSERT (lseek (fd2
, 0, SEEK_CUR
) == -1);
61 ASSERT (errno
== EBADF
);
62 ASSERT (lseek (fd
, 0, SEEK_CUR
) == 2);
64 /* Likewise for an input stream. */
67 f
= fdopen (fd2
, "r");
69 ASSERT (fgetc (f
) == buf
[2]);
70 ASSERT (fclose (f
) == 0);
72 ASSERT (lseek (fd2
, 0, SEEK_CUR
) == -1);
73 ASSERT (errno
== EBADF
);
74 ASSERT (lseek (fd
, 0, SEEK_CUR
) == 3);
76 /* Test that fclose() sets errno if someone else closes the stream
77 fd behind the back of stdio. */
78 #if !defined __ANDROID__ /* fdsan */
80 FILE *fp
= fdopen (fd
, "w+");
82 ASSERT (close (fd
) == 0);
84 ASSERT (fclose (fp
) == EOF
);
85 ASSERT (errno
== EBADF
);
89 /* Test that fclose() sets errno if the stream was constructed with
90 an invalid file descriptor. */
92 FILE *fp
= fdopen (-1, "r");
96 ASSERT (fclose (fp
) == EOF
);
97 ASSERT (errno
== EBADF
);
103 fp
= fdopen (99, "r");
107 ASSERT (fclose (fp
) == EOF
);
108 ASSERT (errno
== EBADF
);
113 ASSERT (remove (BASE
) == 0);
115 return test_exit_status
;