patchline('test.txt', 'a = 5', 132)
patchline('test.txt', 'b = 60', 133)
function patchline(filename, newstring, lineno)
fid1 = fopen(filename, 'r');
if fid1 == -1
error(['Cannot open file ' filename ' for reading.']);
end
tempfilename = 'temp1.txt';
fid2 = fopen(tempfilename, 'w');
if fid2 == -1
error(['Cannot open file ' filename ' for writing.']);
end
line = fgets(fid1);
i = 1;
while line ~= -1
if i == lineno
fprintf(fid2, '%s\n', newstring);
else
fprintf(fid2, '%s', line);
end
line = fgets(fid1);
i = i + 1;
end
st = fclose(fid1);
if st == -1
error(['Cannot close ' filename '.'])
end
st = fclose(fid2);
if st == -1
error(['Cannot close ' tempfilename '.'])
end
if i < lineno
warning(['File ' filename ' has fewer than ' int2str(lineno) 'lines.']);
delete(tempfilename)
else
movefile(tempfilename, filename, 'f')
end