2.9
[glibc/nacl-glibc.git] / stdio-common / tst-fmemopen.c
blob3c06c45c781d32c48855680cfac1e0eaa22e3947
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <sys/mman.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
11 #define TEST_FILE "test-1"
13 int
14 main (void)
16 const char blah[] = "BLAH";
17 FILE *fp;
18 char *mmap_data;
19 int ch, fd;
20 struct stat fs;
21 const char *cp;
23 /* setup the physical file, and use it */
24 if ((fp = fopen (TEST_FILE, "w+")) == NULL)
25 exit (1);
26 if (fwrite (blah, 1, strlen (blah), fp) != strlen (blah))
27 exit (2);
29 rewind (fp);
30 printf ("file: ");
31 cp = blah;
32 while ((ch = getc (fp)) != EOF)
34 fputc (ch, stdout);
35 if (ch != *cp)
37 printf ("\ncharacter %td: '%c' instead of '%c'\n",
38 cp - blah, ch, *cp);
39 exit (1);
41 ++cp;
43 fputc ('\n', stdout);
44 if (ferror (fp))
46 puts ("fp: error");
47 exit (1);
49 if (feof (fp))
50 printf ("fp: EOF\n");
51 else
53 puts ("not EOF");
54 exit (1);
56 fclose (fp);
58 /* Now, mmap the file into a buffer, and do that too */
59 if ((fd = open (TEST_FILE, O_RDONLY)) == -1)
60 exit (3);
61 if (fstat (fd, &fs) == -1)
62 exit (4);
64 if ((mmap_data = (char *) mmap (NULL, fs.st_size, PROT_READ,
65 MAP_SHARED, fd, 0)) == MAP_FAILED)
67 if (errno == ENOSYS)
68 exit (0);
69 exit (5);
72 if ((fp = fmemopen (mmap_data, fs.st_size, "r")) == NULL)
73 exit (1);
75 printf ("mem: ");
76 cp = blah;
77 while ((ch = getc (fp)) != EOF)
79 fputc (ch, stdout);
80 if (ch != *cp)
82 printf ("%td character: '%c' instead of '%c'\n",
83 cp - blah, ch, *cp);
84 exit (1);
86 ++cp;
89 fputc ('\n', stdout);
91 if (ferror (fp))
93 puts ("fp: error");
94 exit (1);
96 if (feof (fp))
97 printf ("fp: EOF\n");
98 else
100 puts ("not EOF");
101 exit (1);
104 fclose (fp);
106 munmap (mmap_data, fs.st_size);
108 unlink (TEST_FILE);
110 return 0;