IoHelper.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #else
  45. #ifdef LMMS_HAVE_UNISTD_H
  46. #include <unistd.h>
  47. #endif
  48. #endif
  49. FILE* F_OPEN_UTF8(std::string const& fname, const char* mode){
  50. #ifdef LMMS_BUILD_WIN32
  51. return _wfopen(toWString(fname).data(), toWString(mode).data());
  52. #else
  53. return fopen(fname.data(), mode);
  54. #endif
  55. }
  56. int fileToDescriptor(FILE* f, bool closeFile = true)
  57. {
  58. int fh;
  59. if (f == nullptr) {return -1;}
  60. #ifdef LMMS_BUILD_WIN32
  61. fh = _dup(_fileno(f));
  62. #else
  63. fh = dup(fileno(f));
  64. #endif
  65. if (closeFile) {fclose(f);}
  66. return fh;
  67. }