1 // RUN: %clangxx -g %s -o %t && %run %t
2 
3 // Newer versions of Android have FDSan, and will fail this test as FDSan will
4 // catch the error instead.
5 // UNSUPPORTED: android
6 
7 #include <assert.h>
8 #include <stdio.h>
9 #include <unistd.h>
10 
main(int argc,char ** argv)11 int main(int argc, char **argv) {
12   FILE *fp = fopen(argv[0], "r");
13   assert(fp);
14 
15   // file should be good upon opening
16   assert(!feof(fp) && !ferror(fp));
17 
18   // read until EOF
19   char buf[BUFSIZ];
20   while (fread(buf, 1, sizeof buf, fp) != 0) {}
21   assert(feof(fp));
22 
23   // clear EOF
24   clearerr(fp);
25   assert(!feof(fp) && !ferror(fp));
26 
27   // get file descriptor
28   int fd = fileno(fp);
29   assert(fd != -1);
30 
31   // break the file by closing underlying descriptor
32   assert(close(fd) != -1);
33 
34   // verify that an error is signalled
35   assert(fread(buf, 1, sizeof buf, fp) == 0);
36   assert(ferror(fp));
37 
38   // clear error
39   clearerr(fp);
40   assert(!feof(fp) && !ferror(fp));
41 
42   // fclose() will return EBADF because of closed fd
43   assert(fclose(fp) == -1);
44   return 0;
45 }
46