MATLAB: Function for editing a file

m script write functionsimulink coder

Dear Techies, I want to read and write a file with some changes. I am able to read a particular line using fgetl().After reading the line I want to edit the line and save it in the same file. What function I need to use for this purpose?
reg, joseph

Best Answer

This possible by using fwrite or fprintf when the number of characters do not change. If it does or could change, there is no other way than reading the complete file, modifying the data and re-write it:
Str = fileread(FileName);
Str = strrep(Str, char([13, 10]), char(10)); % Care for linebreaks
CStr = regexp(Str, char(10), 'split');
CStr{23} = strrep(CStr{23}, 'short string', 'much longer string');
FID = fopen(FileName, 'w'); % or wt
if FID == -1, error('Cannot open file for writing: %s', FileName); end
fprintf(FID, '%s\n', CStr{:});
fclose(FID);