Back to index

glibc  2.9
tst-fmemopen.c
Go to the documentation of this file.
00001 #include <errno.h>
00002 #include <fcntl.h>
00003 #include <stdio.h>
00004 #include <stdlib.h>
00005 #include <string.h>
00006 #include <unistd.h>
00007 #include <sys/mman.h>
00008 #include <sys/stat.h>
00009 #include <sys/types.h>
00010 
00011 #define TEST_FILE "test-1"
00012 
00013 int
00014 main (void)
00015 {
00016   const char blah[] = "BLAH";
00017   FILE *fp;
00018   char *mmap_data;
00019   int ch, fd;
00020   struct stat fs;
00021   const char *cp;
00022 
00023   /* setup the physical file, and use it */
00024   if ((fp = fopen (TEST_FILE, "w+")) == NULL)
00025     exit (1);
00026   if (fwrite (blah, 1, strlen (blah), fp) != strlen (blah))
00027     exit (2);
00028 
00029   rewind (fp);
00030   printf ("file: ");
00031   cp = blah;
00032   while ((ch = getc (fp)) != EOF)
00033     {
00034       fputc (ch, stdout);
00035       if (ch != *cp)
00036        {
00037          printf ("\ncharacter %td: '%c' instead of '%c'\n",
00038                 cp - blah, ch, *cp);
00039          exit (1);
00040        }
00041       ++cp;
00042     }
00043   fputc ('\n', stdout);
00044   if (ferror (fp))
00045     {
00046       puts ("fp: error");
00047       exit (1);
00048     }
00049   if (feof (fp))
00050     printf ("fp: EOF\n");
00051   else
00052     {
00053       puts ("not EOF");
00054       exit (1);
00055     }
00056   fclose (fp);
00057 
00058   /* Now, mmap the file into a buffer, and do that too */
00059   if ((fd = open (TEST_FILE, O_RDONLY)) == -1)
00060     exit (3);
00061   if (fstat (fd, &fs) == -1)
00062     exit (4);
00063 
00064   if ((mmap_data = (char *) mmap (NULL, fs.st_size, PROT_READ,
00065                               MAP_SHARED, fd, 0)) == MAP_FAILED)
00066     {
00067       if (errno == ENOSYS)
00068        exit (0);
00069       exit (5);
00070     }
00071 
00072   if ((fp = fmemopen (mmap_data, fs.st_size, "r")) == NULL)
00073     exit (1);
00074 
00075   printf ("mem: ");
00076   cp = blah;
00077   while ((ch = getc (fp)) != EOF)
00078     {
00079       fputc (ch, stdout);
00080       if (ch != *cp)
00081        {
00082          printf ("%td character: '%c' instead of '%c'\n",
00083                 cp - blah, ch, *cp);
00084          exit (1);
00085        }
00086       ++cp;
00087     }
00088 
00089   fputc ('\n', stdout);
00090 
00091   if (ferror (fp))
00092     {
00093       puts ("fp: error");
00094       exit (1);
00095     }
00096   if (feof (fp))
00097     printf ("fp: EOF\n");
00098   else
00099     {
00100       puts ("not EOF");
00101       exit (1);
00102     }
00103 
00104   fclose (fp);
00105 
00106   munmap (mmap_data, fs.st_size);
00107 
00108   unlink (TEST_FILE);
00109 
00110   return 0;
00111 }