realpath.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdlib.h>
  27. #include <errno.h>
  28. #include <unistd.h>
  29. // Make sure a path only has forward slashes.
  30. char *to_unix_path(char *p) {
  31. if (p != NULL) {
  32. char *pp = p;
  33. while (*pp != 0) {
  34. if (*pp == '\\')
  35. *pp = '/';
  36. ++pp;
  37. }
  38. }
  39. return p;
  40. }
  41. // Implement realpath() using _fullpath and make it use the same error codes as realpath() on unix.
  42. // Also have it return a path with forward slashes only as some code relies on this,
  43. // but _fullpath() returns backward slashes no matter what.
  44. char *realpath(const char *path, char *resolved_path) {
  45. char *ret = NULL;
  46. if (path == NULL) {
  47. errno = EINVAL;
  48. } else if (access(path, R_OK) == 0) {
  49. ret = resolved_path;
  50. if (ret == NULL)
  51. ret = malloc(_MAX_PATH);
  52. if (ret == NULL) {
  53. errno = ENOMEM;
  54. } else {
  55. ret = _fullpath(ret, path, _MAX_PATH);
  56. if (ret == NULL)
  57. errno = EIO;
  58. }
  59. }
  60. return to_unix_path(ret);
  61. }