printenv-test.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <stdio.h>
  2. #ifdef MSWIN
  3. # include <windows.h>
  4. #else
  5. # include <stdlib.h>
  6. #endif
  7. #ifdef MSWIN
  8. int wmain(int argc, wchar_t **argv)
  9. #else
  10. int main(int argc, char **argv)
  11. #endif
  12. {
  13. if (argc != 2) {
  14. return 1;
  15. }
  16. #ifdef MSWIN
  17. wchar_t *value = _wgetenv(argv[1]);
  18. if (value == NULL) {
  19. return 1;
  20. }
  21. int utf8_len = WideCharToMultiByte(CP_UTF8,
  22. 0,
  23. value,
  24. -1,
  25. NULL,
  26. 0,
  27. NULL,
  28. NULL);
  29. if (utf8_len == 0) {
  30. return (int)GetLastError();
  31. }
  32. char *utf8_value = (char *)calloc((size_t)utf8_len, sizeof(char));
  33. utf8_len = WideCharToMultiByte(CP_UTF8,
  34. 0,
  35. value,
  36. -1,
  37. utf8_value,
  38. utf8_len,
  39. NULL,
  40. NULL);
  41. fprintf(stdout, "%s", utf8_value);
  42. free(utf8_value);
  43. #else
  44. char *value = getenv(argv[1]);
  45. if (value == NULL) {
  46. fprintf(stderr, "env var not found: %s", argv[1]);
  47. return 1;
  48. }
  49. fprintf(stdout, "%s", value);
  50. #endif
  51. fflush(stdout);
  52. return 0;
  53. }