tst-mmap-setvbuf.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Test setvbuf on readonly fopen (using mmap stdio).
  2. Copyright (C) 2002-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <unistd.h>
  19. #include <libc-diag.h>
  20. int main (void)
  21. {
  22. char name[] = "/tmp/tst-mmap-setvbuf.XXXXXX";
  23. char buf[4096];
  24. const char * const test = "Let's see if mmap stdio works with setvbuf.\n";
  25. DIAG_PUSH_NEEDS_COMMENT_CLANG;
  26. DIAG_IGNORE_NEEDS_COMMENT_CLANG (3.4, "-Wgnu-folding-constant");
  27. char temp[strlen (test) + 1];
  28. DIAG_POP_NEEDS_COMMENT_CLANG;
  29. int fd = mkstemp (name);
  30. FILE *f;
  31. if (fd == -1)
  32. {
  33. printf ("%u: cannot open temporary file: %m\n", __LINE__);
  34. exit (1);
  35. }
  36. f = fdopen (fd, "w");
  37. if (f == NULL)
  38. {
  39. printf ("%u: cannot fdopen temporary file: %m\n", __LINE__);
  40. exit (1);
  41. }
  42. fputs (test, f);
  43. fclose (f);
  44. f = fopen (name, "rm");
  45. if (f == NULL)
  46. {
  47. printf ("%u: cannot fopen temporary file: %m\n", __LINE__);
  48. exit (1);
  49. }
  50. if (setvbuf (f, buf, _IOFBF, sizeof buf))
  51. {
  52. printf ("%u: setvbuf failed: %m\n", __LINE__);
  53. exit (1);
  54. }
  55. if (fread (temp, 1, strlen (test), f) != strlen (test))
  56. {
  57. printf ("%u: couldn't read the file back: %m\n", __LINE__);
  58. exit (1);
  59. }
  60. temp [strlen (test)] = '\0';
  61. if (strcmp (test, temp))
  62. {
  63. printf ("%u: read different string than was written:\n%s%s",
  64. __LINE__, test, temp);
  65. exit (1);
  66. }
  67. fclose (f);
  68. unlink (name);
  69. exit (0);
  70. }