www.gusucode.com > mbcdata 工具箱 matlab 源码程序 > mbcdata/private/pSetupFileWrite.m
function [OK, CleanupFcn] = pSetupFileWrite(Filename) %PSETUPFILEWRITE Perform file-writing tasks for cal interface functions. % % [OK, CLEANUPFCN] = PSETUPFILEWRITE(FILENAME) checks thtat FILENAME is % writable. If it is, the file is moved to a temporary location ready % for the new file to be created. Once the new file has been written % successfully, the provided function handle CLEANUPFCN should be called % to remove the temporary data. If the writing failed for any reason, % CLEANUPFCN(false) may be called in order to replace the original file. % Copyright 2005-2014 The MathWorks, Inc. OK = false; CleanupFcn = @i_cleanup; TempLocation = ''; if exist(Filename, 'file') && ~exist(Filename, 'dir') % Check file is writable fid = fopen(Filename, 'a'); OK = (fid~=-1); if OK fclose(fid); else msg = sprintf('Unable to write to file "%s". Ensure the file is not read-only.', Filename); h = errordlg(msg, 'Error', 'modal'); waitfor(h); end % Go ahead with move if possible if OK TempLocation = tempname; [~, TempLocation]= fileparts(TempLocation); try movefile(Filename, TempLocation); catch TempLocation = tempname; try movefile(Filename, TempLocation); catch % Could not move file to a temp location. Just delete it % instead TempLocation = ''; delete(Filename); end end end elseif ~exist(Filename, 'file') && ~exist(Filename, 'dir') OK = true; end function i_cleanup(action) if ~isempty(TempLocation) if nargin && ~action % move temp file back to original location try movefile(TempLocation, Filename, 'f'); end else % delete temp file try delete(TempLocation); end end end end end