MATLAB: How to begin overwriting a txt file from a specific line

beginnerfidfopenfprintfMATLABtxttxtoutput

I'm new to Matlab and I'm not experienced in programming.
The matter is that I have to produce a single output.txt file where I have to print information from 2 different scripts without deleting previous results. In the script1 I used commands like fid, fopen, output.txt 'w' fprintf.. In the second one I would do the same if only I didn't lose the output written before in doing so.
Thanks in advance.

Best Answer

You can fopen the file with 'r+' permission.
You cannot go directly to the the desired line. You can though fgetl or fgets to read in the lines before that point.
Once you have read in the lines before the point that you want to start writing, you need to use fseek() to seek 0 bytes relative to the current point. That sounds like a waste of time, I know, but it tells matlab to get ready to switch to writing.
Then you can start writing the new content.
Warning: any bytes that you do not overwrite will be left the file, and there is no way to discard the rest of a file, and no way to move the rest of the file further left or right, so if you do not replace with exactly the same number of bytes, or else you replace everything to and possibly past the end of file, you are likely to end up with content that you do not want.
Because replacement in the middle of a text file must be for exactly the same number of bytes (not characters), it is almost always a better choice to Don't Do That!
That is, in most cases with text files you should instead create a new file containing the content you want (possibly reading most of it from the old file) instead of changing the inside of an existing text file.