How to add text to existing file?
Show older comments
Hi all,
I have a text file data.txt given as:
abc EXECUTE
efg
GHI EXECUTE
EXECUTE
asg
EXECUTE
I want to insert text after EXECUTE (when it appears as the first word).
I want this text output for the same file name.
abc EXECUTE
efg
GHI EXECUTE
EXECUTE
Write something after Execute
asg
EXECUTE
Write something after Execute
I am trying to use MATLAB to precess this. This the code I am trying to write:
%-----------------------------------------------------------
clc
clear all
close all
fid= fopen('data.txt','r+');
line_no=0;
tline=0;
while tline ~= -1 & line_no<6
line_no=line_no+1
tline=fgetl(fid)
if length(findstr('EXECUTE',tline))>0 %& length(tline)<10
fprintf(fid,'\n Write something after Execute');
tline=fgetl(fid)
end
end
%---------------------------------------------------------------------
However, the text output is little weird. Any help is appreciated.
Sincerely,
Mahendra.
Answers (1)
Walter Roberson
on 6 Jun 2012
1 vote
You need to write the output to a different file, copying the input you want to keep, (and possibly renaming that file to the original name once you are finished the processing.) Writing to a text file "in place" is tricky and is only really possible in fairly limited circumstances.
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!