ExtractingFilePath.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // ExtractingFilePath.cpp
  2. #include "StdAfx.h"
  3. #include "ExtractingFilePath.h"
  4. static UString ReplaceIncorrectChars(const UString &s)
  5. {
  6. #ifdef _WIN32
  7. UString res;
  8. for (int i = 0; i < s.Length(); i++)
  9. {
  10. wchar_t c = s[i];
  11. if (c < 0x20 || c == '*' || c == '?' || c == '<' || c == '>' || c == '|' || c == ':' || c == '"')
  12. c = '_';
  13. res += c;
  14. }
  15. return res;
  16. #else
  17. return s;
  18. #endif
  19. }
  20. #ifdef _WIN32
  21. static const wchar_t *g_ReservedNames[] =
  22. {
  23. L"CON", L"PRN", L"AUX", L"NUL"
  24. };
  25. static bool CheckTail(const UString &name, int len)
  26. {
  27. int dotPos = name.Find(L'.');
  28. if (dotPos < 0)
  29. dotPos = name.Length();
  30. UString s = name.Left(dotPos);
  31. s.TrimRight();
  32. return (s.Length() != len);
  33. }
  34. static bool CheckNameNum(const UString &name, const wchar_t *reservedName)
  35. {
  36. int len = MyStringLen(reservedName);
  37. if (name.Length() <= len)
  38. return true;
  39. if (name.Left(len).CompareNoCase(reservedName) != 0)
  40. return true;
  41. wchar_t c = name[len];
  42. if (c < L'0' || c > L'9')
  43. return true;
  44. return CheckTail(name, len + 1);
  45. }
  46. static bool IsSupportedName(const UString &name)
  47. {
  48. for (int i = 0; i < sizeof(g_ReservedNames) / sizeof(g_ReservedNames[0]); i++)
  49. {
  50. const wchar_t *reservedName = g_ReservedNames[i];
  51. int len = MyStringLen(reservedName);
  52. if (name.Length() < len)
  53. continue;
  54. if (name.Left(len).CompareNoCase(reservedName) != 0)
  55. continue;
  56. if (!CheckTail(name, len))
  57. return false;
  58. }
  59. if (!CheckNameNum(name, L"COM"))
  60. return false;
  61. return CheckNameNum(name, L"LPT");
  62. }
  63. #endif
  64. static UString GetCorrectFileName(const UString &path)
  65. {
  66. if (path == L".." || path == L".")
  67. return UString();
  68. return ReplaceIncorrectChars(path);
  69. }
  70. void MakeCorrectPath(UStringVector &pathParts)
  71. {
  72. for (int i = 0; i < pathParts.Size();)
  73. {
  74. UString &s = pathParts[i];
  75. s = GetCorrectFileName(s);
  76. if (s.IsEmpty())
  77. pathParts.Delete(i);
  78. else
  79. {
  80. #ifdef _WIN32
  81. if (!IsSupportedName(s))
  82. s = (UString)L"_" + s;
  83. #endif
  84. i++;
  85. }
  86. }
  87. }