stripfile.m 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function [f,file] = stripfile(x,flag,sep)
  2. % function [f,file] = stripfile(x,flag,sep)
  3. %
  4. % <x> is a string referring to a file (it is okay if the file
  5. % does not actually exist). if <x> ends in /, we automatically
  6. % act as if that / does not exist.
  7. % <flag> (optional) is whether to swap the output arguments. default: 0.
  8. % <sep> (optional) is the actual "/" character to use. default is
  9. % the output of filesep.m.
  10. %
  11. % if <flag> is 0,
  12. % return <f> as the string but with the file name removed.
  13. % return <file> with the file name.
  14. % if <flag> is 1, these arguments are swapped.
  15. %
  16. % history:
  17. % 2014/07/14 - make more general by defaulting <sep> to filesep.m.
  18. %
  19. % example:
  20. % isequal(stripfile('blah/temp.png',[],'/'),'blah/')
  21. % isequal(stripfile('temp.png',[],'/'),'')
  22. % isequal(stripfile('ok/blah/',1,'/'),'blah')
  23. % input
  24. if ~exist('flag','var') || isempty(flag)
  25. flag = 0;
  26. end
  27. if ~exist('sep','var') || isempty(sep)
  28. sep = filesep;
  29. end
  30. % find any /
  31. locs = strfind(x,sep);
  32. % if none, return ''
  33. if isempty(locs)
  34. f = '';
  35. file = x;
  36. % otherwise, return entire string up to the last /
  37. else
  38. if locs(end)==length(x) % ignore trailing /
  39. x = x(1:end-1);
  40. locs = locs(1:end-1);
  41. end
  42. if isempty(locs)
  43. f = '';
  44. file = x;
  45. else
  46. f = x(1:locs(end));
  47. file = x(locs(end)+1:end);
  48. end
  49. end
  50. % swap the output?
  51. if flag
  52. [f,file] = swap(f,file);
  53. end