function file_mask = mktemp( file_mask ) % function file_mask = mktemp( file_mask ) % % Creates an almost guaranteed unique file name, given some template with one % or more contiguous 'X' characters. Once a unique name is found, a blank file % is created with that name. This is done to minimize potential race % conditions (but they definitely do still exist!) % % See also: the mktemp manpage, from which this function was inspired % % Joshua V. Dillon; Feb. 20, 2007; jvdillon AAT purdue DDOT edu tries = 100; % ensure the supplied path is valid pos = strfind(file_mask,'/'); if length(pos)~=0 & ~exist(file_mask(1:pos(end)),'dir') error(['directory "' file_mask(1:pos(end)) '" doesn''t exist']); end % find the start and end of the longest chain of X's mend = regexp(file_mask,'X+','end'); if numel(mend)==0 error('invalid filename mask: must contain one or more ''X'''); end mstart = regexp(file_mask,'X+','start'); [digs pos]=max(1+mend-mstart); % replace the X's and see if the file exists for ii=1:tries num = num2str(ceil(rand*10^digs)); file_mask(mstart(pos):mend(pos)) = [repmat('0',1,digs-length(num)) num]; if ~exist(file_mask,'file') % NB: Although race conditions are still possible, this should help. % This also has the advantage of verifying one can actually write % to this file. fclose(fopen(file_mask,'w')); return; end end file_mask = ''; error(['couldn''t create a unique file name after ' ... num2str(tries) ' tries--giving up!']);