www.gusucode.com > slcidemos工具箱matlab源码程序 > slcidemos/slcidemo_modifycode.m

    function varargout = slcidemo_modifycode(file, marker, oldsubstr, ...
    newsubstr, varargin)
% SLCIDEMO_MODIFYCODE - Modify a file for a given replacement string.
%
%   VARARGOUT = SLCIDEMO_MODIFYCODE(FILE,MARKER,OLDSUBSTR,NEWSUBSTR,...)
%
%   FILE      - Name of the file to modify
%   MARKER    - Substring is not replaced until after this marker is found
%   OLDSUBSTR - Substring to be replaced
%   NEWSUBSTR - New substring
%   VARARGIN  - Quiets the output display if true (default is false)
% 
%   VARARGOUT - Line number for which the modification occurred, and
%               [] if no action was taken.
% Example usage:
%
%   >> ln = slcidemo_modifycode('slcidemo_roll.c','<S1>/Or', '||', '&&');
%
%   Replaces occurrences of '||' with '&&' on the first line following
%   the line containing '<S1>/Or' in slcidemo_roll.c, and returns the
%   line number for which the modification occurred.

%
% Copyright 1994-2011 The MathWorks, Inc.

if nargin == 5
    quiet = varargin{1};
else
    quiet = false;
end

% create a backup of the file
backup_file = [file,'.backup'];
copyfile(file, backup_file, 'f')

fid_in=fopen(backup_file,'r');
fid_out=fopen(file,'w');

foundMarker = false;
foundSubstr = false;

linecount = 0;
linenum = [];

while 1
    tline = fgetl(fid_in);
    if ~ischar(tline), break, end
    linecount = linecount + 1;
    if strfind(tline, marker)
        foundMarker = true;
    end
    if foundMarker && ~foundSubstr && ~isempty(strfind(tline,oldsubstr))
        linenum = linecount;
        if ~quiet
            fprintf('Modified line %g of file %s.\n', linenum, file);
            fprintf('Before: %s\n',tline)
        end
        tline = strrep(tline,oldsubstr,newsubstr);
        foundSubstr = true;
        if ~quiet
            fprintf('After : %s\n',tline)
        end
    end
    fprintf(fid_out,'%s\n',tline);
end

fclose(fid_in);
fclose(fid_out);

if nargout == 1
    varargout = {linenum};
end

end

% LocalWords:  OLDSUBSTR NEWSUBSTR ln