test_format.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Host test for the stdio formatting core. */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stddef.h>
  5. int errno;
  6. static int failures;
  7. static void check(const char *got, const char *want)
  8. {
  9. if (strcmp(got, want)) {
  10. printf("format mismatch: got [%s] want [%s]\n", got, want);
  11. failures++;
  12. }
  13. }
  14. int main(void)
  15. {
  16. char b[2048];
  17. snprintf(b, sizeof(b), "%d %u %x %s %c %%", -42, 42u,
  18. 0xdeadbeefu, "hi", 'Z');
  19. check(b, "-42 42 deadbeef hi Z %");
  20. snprintf(b, sizeof(b), "%08d %-5s %.3s %+d % d",
  21. 42, "ab", "abcdef", 7, 7);
  22. check(b, "00000042 ab abc +7 7");
  23. snprintf(b, sizeof(b), "%lld %llu %llx", 1234567890123LL,
  24. 18446744073709551615ULL, 0xdeadbeefcafebabeULL);
  25. check(b, "1234567890123 18446744073709551615 deadbeefcafebabe");
  26. snprintf(b, sizeof(b), "%f %.2f %.0f %e %.3e %g %.3g",
  27. 1.5, 1.005, 2.5, 1234.5, 0.0012345, 1000000.0, 0.00012345);
  28. check(b, "1.500000 1.00 2 1.234500e+03 1.234e-03 1e+06 0.000123");
  29. snprintf(b, sizeof(b), "%.20f", 1.0 / 3.0);
  30. check(b, "0.33333333333333331483");
  31. snprintf(b, sizeof(b), "%.20f", 0.1);
  32. check(b, "0.10000000000000000555");
  33. snprintf(b, sizeof(b), "%.0f %.0f %.0f %.0f", 0.5, 1.5, 2.5, 3.5);
  34. check(b, "0 2 2 4");
  35. snprintf(b, sizeof(b), "%.2f %.2f %.2f", 1.005, 2.675, 9.999);
  36. check(b, "1.00 2.67 10.00");
  37. snprintf(b, sizeof(b), "%g %g %g %g", 100000.0, 1000000.0,
  38. 0.0001, 0.00001);
  39. check(b, "100000 1e+06 0.0001 1e-05");
  40. snprintf(b, sizeof(b), "%f", -0.0);
  41. check(b, "-0.000000");
  42. {
  43. char *nullp = 0;
  44. const char *six = "abcdef";
  45. snprintf(b, sizeof(b), "%s", nullp);
  46. check(b, "(null)");
  47. snprintf(b, 5, "%s", six);
  48. check(b, "abcd");
  49. }
  50. snprintf(b, sizeof(b), "%p", (void *)0x1234);
  51. check(b, "0x1234");
  52. if (failures)
  53. printf("format test: %d failure(s)\n", failures);
  54. else
  55. printf("format test: OK\n");
  56. return failures != 0;
  57. }