IoHelper.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * IoHelper.h - helper functions for file I/O
  3. *
  4. * Copyright (c) 2018 Hyunjin Song <tteu.ingog/at/gmail.com>
  5. *
  6. * This file is part of LMMS - https://lmms.io
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public
  19. * License along with this program (see COPYING); if not, write to the
  20. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301 USA.
  22. *
  23. */
  24. #include "lmmsconfig.h"
  25. #include <cstdio>
  26. #ifdef _WIN32
  27. #include <windows.h>
  28. std::wstring toWString(const std::string& s)
  29. {
  30. std::wstring ret;
  31. int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(),
  32. s.length(), nullptr, 0);
  33. if (len == 0)
  34. {
  35. return ret;
  36. }
  37. ret.resize(len);
  38. MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s.length(), &ret[0], len);
  39. return ret;
  40. }
  41. #endif
  42. #ifdef LMMS_BUILD_WIN32
  43. #include <io.h>
  44. #define F_OPEN_UTF8(a, b) _wfopen(toWString(a).data(), L##b)
  45. #else
  46. #ifdef LMMS_HAVE_UNISTD_H
  47. #include <unistd.h>
  48. #endif
  49. #define F_OPEN_UTF8(a, b) fopen((a).data(), b)
  50. #endif
  51. int fileToDescriptor(FILE* f, bool closeFile = true)
  52. {
  53. int fh;
  54. if (f == NULL) {return -1;}
  55. #ifdef LMMS_BUILD_WIN32
  56. fh = _dup(_fileno(f));
  57. #else
  58. fh = dup(fileno(f));
  59. #endif
  60. if (closeFile) {fclose(f);}
  61. return fh;
  62. }