first_line_to_delete = 3;
num_lines_to_delete = 1;
infilename = 'YourFile.txt';
[pathstr, file, ext] = fileparts(infilename);
backfile = fullfile(pathstr, [file '.bak']);
if strcmp(infilename, backfile)
error('I refuse to edit a backup file! Nothing has been changed.');
end
outfile = tempfile;
fin = fopen(infilename, 'r');
if fin < 0; error('Input file does not exist'); end
fout = fopen(tfile, 'w');
if fout < 0
fclose(fin);
error('Could not open temporary output file');
end
for K = 1 : first_line_to_delete - 1;
inline = fgets(fin);
if ~ischar(inline); break; end;
fwrite(fout, inline);
end
for K = 1 : num_lines_to_delete
if ~ischar(inline); break; end
inline = fgets(fin);
end
while ischar(inline)
inline = fgets(fin);
if ischar(inline)
fwrite(fout, inline);
end
end
fclose(fin);
fclose(fout);
status = movefile(infilename, backfile);
if ~status
if strcmp(infilename, backfile)
fprintf(2, 'Good thing your programmer is paranoid about people overriding\nsanity checks, because something went wrong and you nearly lost your file!\n');
else
delete(backfile);
end
error('Could not rename file to .bak, file left untouched');
else
status = movefile(outfile, infilename);
if ~status
error( ['Could not rename temp file to original name, original moved to ', backfile]);
end
end
Best Answer