function [f,file] = stripfile(x,flag,sep) <x> is a string referring to a file (it is okay if the file does not actually exist). if <x> ends in /, we automatically act as if that / does not exist. <flag> (optional) is whether to swap the output arguments. default: 0. <sep> (optional) is the actual "/" character to use. default is the output of filesep.m. if <flag> is 0, return <f> as the string but with the file name removed. return <file> with the file name. if <flag> is 1, these arguments are swapped. history: 2014/07/14 - make more general by defaulting <sep> to filesep.m. example: isequal(stripfile('blah/temp.png',[],'/'),'blah/') isequal(stripfile('temp.png',[],'/'),'') isequal(stripfile('ok/blah/',1,'/'),'blah')
0001 function [f,file] = stripfile(x,flag,sep) 0002 0003 % function [f,file] = stripfile(x,flag,sep) 0004 % 0005 % <x> is a string referring to a file (it is okay if the file 0006 % does not actually exist). if <x> ends in /, we automatically 0007 % act as if that / does not exist. 0008 % <flag> (optional) is whether to swap the output arguments. default: 0. 0009 % <sep> (optional) is the actual "/" character to use. default is 0010 % the output of filesep.m. 0011 % 0012 % if <flag> is 0, 0013 % return <f> as the string but with the file name removed. 0014 % return <file> with the file name. 0015 % if <flag> is 1, these arguments are swapped. 0016 % 0017 % history: 0018 % 2014/07/14 - make more general by defaulting <sep> to filesep.m. 0019 % 0020 % example: 0021 % isequal(stripfile('blah/temp.png',[],'/'),'blah/') 0022 % isequal(stripfile('temp.png',[],'/'),'') 0023 % isequal(stripfile('ok/blah/',1,'/'),'blah') 0024 0025 % input 0026 if ~exist('flag','var') || isempty(flag) 0027 flag = 0; 0028 end 0029 if ~exist('sep','var') || isempty(sep) 0030 sep = filesep; 0031 end 0032 0033 % find any / 0034 locs = strfind(x,sep); 0035 0036 % if none, return '' 0037 if isempty(locs) 0038 f = ''; 0039 file = x; 0040 % otherwise, return entire string up to the last / 0041 else 0042 if locs(end)==length(x) % ignore trailing / 0043 x = x(1:end-1); 0044 locs = locs(1:end-1); 0045 end 0046 if isempty(locs) 0047 f = ''; 0048 file = x; 0049 else 0050 f = x(1:locs(end)); 0051 file = x(locs(end)+1:end); 0052 end 0053 end 0054 0055 % swap the output? 0056 if flag 0057 [f,file] = swap(f,file); 0058 end