How do you write to a fopen text file without deleting previous text?
Show older comments
I'm writing the results of my program to a text file. But every time I run the program and open the text file using fopen, it overwrites everything that was previously written in that file. What can I do to prevent it overwriting the previous text?
Im opening the file using
fileID = fopen('myfile.txt','r+');
and writing to it
fprintf(fileID,'%d',Number(num));
Accepted Answer
More Answers (2)
Stephen23
on 2 Apr 2016
Simply use the append option a:
fileID = fopen('myfile.txt','a+');
That is it.
1 Comment
Image Analyst
on 2 Apr 2016
He never mentioned append, but I think you might be right. If only he had mentioned that at first....
Muhammad Usman Saleem
on 2 Apr 2016
Edited: Muhammad Usman Saleem
on 2 Apr 2016
change this line to
fileID = fopen('myfile.txt','w'); % opening for writing only
r+ for both reading and writing. Which change previous content
5 Comments
Recap
on 2 Apr 2016
Muhammad Usman Saleem
on 2 Apr 2016
Edited: Muhammad Usman Saleem
on 2 Apr 2016
have you define Number as matrix? and loop over with index variable name num?
if possible to share with me your text file what you want to write in it
Recap
on 2 Apr 2016
Muhammad Usman Saleem
on 2 Apr 2016
Edited: Muhammad Usman Saleem
on 2 Apr 2016
what is your matrix Number? how can it contains string? I am supperise to know matrix with string and numeric?
Recap
on 2 Apr 2016
Categories
Find more on Low-Level File I/O 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!