r+ and text file length

조회 수: 6 (최근 30일)
Keith Holmlund
Keith Holmlund 2018년 6월 25일
편집: per isakson 2018년 6월 25일
I had asked in a previous question https://www.mathworks.com/matlabcentral/answers/406987-fprintf-leaving-remainder-of-line about fprintf leaving text on a new line. I was opening a file using r+ before changing text and rewriting the file. I have noticed since then if I change the text in a manner which changes the length of the text file (ex apple vs bosenberry), it will leave text in a new line.
I have been able to get around this by closing the file then reopening it in w+ before using fprintf to rewrite the file then closing it at the end of the function. Is it a limitation of r+ that it is bound by the length of the text file or is there a way to get around it without having to close and reopen the file?
  댓글 수: 1
dpb
dpb 2018년 6월 25일
That was the point Jan and Walter made in the previous posting -- reopening/reposition a file does not delete any existing content of the file so that if you make changes and rewrite data that is shorter than what was there before, everything from the last character you write forward is still in the file.
If you want entirely new content in the file, the only reliable was in Matlab is to close and reopen it. Otherwise, you'll get the desired result if the new file content is as long or longer than the original, but if shorter, then you get the result you see.
It was possible in the original code you showed to have computed the wrong size but that is, while a coding error, a diversion from the more fundamental issue.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by