Write to file inside a loop

3 views (last 30 days)
Mini Me
Mini Me on 6 Mar 2013
I have this program where I open a file and write data points in it but the problem is I have to do that inside a loop. it goes:
for k=1:1:128
fid=fopen('myfile2.txt','w+') % I write input to that file and pass it to my
exe file
the 4th input (input4) is being taken from a diff file.txt
M= sscanf(result,'%s')
more_result=[ Val M]
frpintf(Fid2,'%s', more_result)
Then I sscanf the results to get the a specific value (M) that I want. and I want to write Val and Z in another file but I only get the last value of each in the file. because fopen(fid,'w+') keep updating inside the loop. using a+ plus doesn't help and it keeps appending and never updates after the program is done running. RIght now I am using a+ then I manually delete the content of that file after i'm done running..writing outside the loop gives me error. is there a way I can clear the file after each run? Thanks

Answers (2)

Walter Roberson
Walter Roberson on 7 Mar 2013
Use 'a+' to append. You can delete() the file when appropriate, and 'a+' will create it if need be.

Mini Me
Mini Me on 7 Mar 2013
Negative, a+ keep appending it which means after the data is run once they are saved there when i run it again it adds up more data instead of discard what was already there first. using w+ keeps updating inside the loop and only save the last data points because it keeps updating the previous ones. I want it only to update after everytime i run it not inside the loop. Im not sure if that makes sense..and delete() did not do a thing
Mini Me
Mini Me on 7 Mar 2013
well savin the last data mean the least point it get from the first file when the loop reaches 128..update after every run means writing all the points to the myfile3.txt file without updating it everytime it the loops increments and pick up another point which is what it does using w+ and also opening the file outside the loop. appending is the only one that works but once it's done running and I running again its add up 128 data points on top of what it already saved in that file...it only append not update

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!