tst_wprintf2.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* Test case by Yoshito Kawada <KAWADA@jp.ibm.com>. */
  2. #include <errno.h>
  3. #include <error.h>
  4. #include <fcntl.h>
  5. #include <locale.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <unistd.h>
  10. #include <wchar.h>
  11. int
  12. main (int argc, char *argv[])
  13. {
  14. int a = 3;
  15. int fd;
  16. char name[] = "/tmp/wprintf.out.XXXXXX";
  17. FILE *fp;
  18. char buf[100];
  19. size_t len;
  20. int res = 0;
  21. fd = mkstemp (name);
  22. if (fd == -1)
  23. error (EXIT_FAILURE, errno, "cannot open temporary file");
  24. unlink (name);
  25. setlocale (LC_ALL, "en_US.UTF-8");
  26. fp = fdopen (dup (fd), "w");
  27. if (fp == NULL)
  28. error (EXIT_FAILURE, errno, "fdopen(,\"w\")");
  29. fwprintf (fp, L"test start");
  30. fwprintf (fp, L" int %d\n", a);
  31. /* String with precision. */
  32. fwprintf (fp, L"1[%6.3s]\n", argv[1]);
  33. fclose (fp);
  34. fp = fdopen (dup (fd), "a");
  35. if (fp == NULL)
  36. error (EXIT_FAILURE, errno, "fdopen(,\"a\")");
  37. setvbuf (fp, NULL, _IONBF, 0);
  38. /* fwprintf to unbuffered stream. */
  39. fwprintf (fp, L"hello.\n");
  40. fclose (fp);
  41. /* Now read it back in. This time using multibyte functions. */
  42. lseek (fd, SEEK_SET, 0);
  43. fp = fdopen (fd, "r");
  44. if (fp == NULL)
  45. error (EXIT_FAILURE, errno, "fdopen(,\"r\")");
  46. if (fgets (buf, sizeof buf, fp) != buf)
  47. error (EXIT_FAILURE, errno, "first fgets");
  48. len = strlen (buf);
  49. if (buf[len - 1] == '\n')
  50. --len;
  51. else
  52. {
  53. puts ("newline missing after first line");
  54. res = 1;
  55. }
  56. printf ("1st line: \"%.*s\" -> %s\n", (int) len, buf,
  57. strncmp (buf, "test start int 3", len) == 0 ? "OK" : "FAIL");
  58. res |= strncmp (buf, "test start int 3", len) != 0;
  59. if (fgets (buf, sizeof buf, fp) != buf)
  60. error (EXIT_FAILURE, errno, "second fgets");
  61. len = strlen (buf);
  62. if (buf[len - 1] == '\n')
  63. --len;
  64. else
  65. {
  66. puts ("newline missing after second line");
  67. res = 1;
  68. }
  69. printf ("2nd line: \"%.*s\" -> %s\n", (int) len, buf,
  70. strncmp (buf, "1[ Som]", len) == 0 ? "OK" : "FAIL");
  71. res |= strncmp (buf, "1[ Som]", len) != 0;
  72. if (fgets (buf, sizeof buf, fp) != buf)
  73. error (EXIT_FAILURE, errno, "third fgets");
  74. len = strlen (buf);
  75. if (buf[len - 1] == '\n')
  76. --len;
  77. else
  78. {
  79. puts ("newline missing after third line");
  80. res = 1;
  81. }
  82. printf ("3rd line: \"%.*s\" -> %s\n", (int) len, buf,
  83. strncmp (buf, "hello.", len) == 0 ? "OK" : "FAIL");
  84. res |= strncmp (buf, "hello.", len) != 0;
  85. return res;
  86. }