tst_swprintf.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. #include <wchar.h>
  3. #include <sys/types.h>
  4. static wchar_t buf[100];
  5. #define nbuf (sizeof (buf) / sizeof (buf[0]))
  6. static const struct
  7. {
  8. size_t n;
  9. const char *str;
  10. ssize_t exp;
  11. } tests[] =
  12. {
  13. { nbuf, "hello world", 11 },
  14. { 0, "hello world", -1 },
  15. { 0, "", -1 },
  16. { nbuf, "", 0 }
  17. };
  18. int
  19. main (int argc, char *argv[])
  20. {
  21. size_t n;
  22. int result = 0;
  23. puts ("test 1");
  24. n = swprintf (buf, nbuf, L"Hello %s", "world");
  25. if (n != 11)
  26. {
  27. printf ("incorrect return value: %zd instead of 11\n", n);
  28. result = 1;
  29. }
  30. else if (wcscmp (buf, L"Hello world") != 0)
  31. {
  32. printf ("incorrect string: L\"%ls\" instead of L\"Hello world\"\n", buf);
  33. result = 1;
  34. }
  35. puts ("test 2");
  36. n = swprintf (buf, nbuf, L"Is this >%g< 3.1?", 3.1);
  37. if (n != 18)
  38. {
  39. printf ("incorrect return value: %zd instead of 18\n", n);
  40. result = 1;
  41. }
  42. else if (wcscmp (buf, L"Is this >3.1< 3.1?") != 0)
  43. {
  44. printf ("incorrect string: L\"%ls\" instead of L\"Is this >3.1< 3.1?\"\n",
  45. buf);
  46. result = 1;
  47. }
  48. for (n = 0; n < sizeof (tests) / sizeof (tests[0]); ++n)
  49. {
  50. ssize_t res = swprintf (buf, tests[n].n, L"%s", tests[n].str);
  51. if (tests[n].exp < 0 && res >= 0)
  52. {
  53. printf ("swprintf (buf, %Zu, L\"%%s\", \"%s\") expected to fail\n",
  54. tests[n].n, tests[n].str);
  55. result = 1;
  56. }
  57. else if (tests[n].exp >= 0 && tests[n].exp != res)
  58. {
  59. printf ("swprintf (buf, %Zu, L\"%%s\", \"%s\") expected to return %Zd, but got %Zd\n",
  60. tests[n].n, tests[n].str, tests[n].exp, res);
  61. result = 1;
  62. }
  63. else
  64. printf ("swprintf (buf, %Zu, L\"%%s\", \"%s\") OK\n",
  65. tests[n].n, tests[n].str);
  66. }
  67. if (swprintf (buf, nbuf, L"%.0s", "foo") != 0
  68. || wcslen (buf) != 0)
  69. {
  70. printf ("swprintf (buf, %Zu, L\"%%.0s\", \"foo\") create some output\n",
  71. nbuf);
  72. result = 1;
  73. }
  74. if (swprintf (buf, nbuf, L"%.0ls", L"foo") != 0
  75. || wcslen (buf) != 0)
  76. {
  77. printf ("swprintf (buf, %Zu, L\"%%.0ls\", L\"foo\") create some output\n",
  78. nbuf);
  79. result = 1;
  80. }
  81. return result;
  82. }