Back to index

glibc  2.9
tst_swprintf.c
Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <wchar.h>
00003 #include <sys/types.h>
00004 
00005 
00006 static wchar_t buf[100];
00007 #define nbuf (sizeof (buf) / sizeof (buf[0]))
00008 static const struct
00009 {
00010   size_t n;
00011   const char *str;
00012   ssize_t exp;
00013 } tests[] =
00014   {
00015     { nbuf, "hello world", 11 },
00016     { 0, "hello world", -1 },
00017     { 0, "", -1 },
00018     { nbuf, "", 0 }
00019   };
00020 
00021 int
00022 main (int argc, char *argv[])
00023 {
00024   size_t n;
00025   int result = 0;
00026 
00027   puts ("test 1");
00028   n = swprintf (buf, nbuf, L"Hello %s", "world");
00029   if (n != 11)
00030     {
00031       printf ("incorrect return value: %zd instead of 11\n", n);
00032       result = 1;
00033     }
00034   else if (wcscmp (buf, L"Hello world") != 0)
00035     {
00036       printf ("incorrect string: L\"%ls\" instead of L\"Hello world\"\n", buf);
00037       result = 1;
00038     }
00039 
00040   puts ("test 2");
00041   n = swprintf (buf, nbuf, L"Is this >%g< 3.1?", 3.1);
00042   if (n != 18)
00043     {
00044       printf ("incorrect return value: %zd instead of 18\n", n);
00045       result = 1;
00046     }
00047   else if (wcscmp (buf, L"Is this >3.1< 3.1?") != 0)
00048     {
00049       printf ("incorrect string: L\"%ls\" instead of L\"Is this >3.1< 3.1?\"\n",
00050              buf);
00051       result = 1;
00052     }
00053 
00054   for (n = 0; n < sizeof (tests) / sizeof (tests[0]); ++n)
00055     {
00056       ssize_t res = swprintf (buf, tests[n].n, L"%s", tests[n].str);
00057 
00058       if (tests[n].exp < 0 && res >= 0)
00059        {
00060          printf ("swprintf (buf, %Zu, L\"%%s\", \"%s\") expected to fail\n",
00061                 tests[n].n, tests[n].str);
00062          result = 1;
00063        }
00064       else if (tests[n].exp >= 0 && tests[n].exp != res)
00065        {
00066          printf ("swprintf (buf, %Zu, L\"%%s\", \"%s\") expected to return %Zd, but got %Zd\n",
00067                 tests[n].n, tests[n].str, tests[n].exp, res);
00068          result = 1;
00069        }
00070       else
00071        printf ("swprintf (buf, %Zu, L\"%%s\", \"%s\") OK\n",
00072               tests[n].n, tests[n].str);
00073     }
00074 
00075   if (swprintf (buf, nbuf, L"%.0s", "foo") != 0
00076       || wcslen (buf) != 0)
00077     {
00078       printf ("swprintf (buf, %Zu, L\"%%.0s\", \"foo\") create some output\n",
00079              nbuf);
00080       result = 1;
00081     }
00082 
00083   if (swprintf (buf, nbuf, L"%.0ls", L"foo") != 0
00084       || wcslen (buf) != 0)
00085     {
00086       printf ("swprintf (buf, %Zu, L\"%%.0ls\", L\"foo\") create some output\n",
00087              nbuf);
00088       result = 1;
00089     }
00090 
00091   return result;
00092 }