fprintf leaving remainder of line

조회 수: 3 (최근 30일)
Keith Holmlund
Keith Holmlund 2018년 6월 22일
댓글: Walter Roberson 2018년 6월 22일
I am reading a txt file into matlab using fopen then textscan. the text is reading into a single cell that 43x1 (So if I wanted to get line 43 I would enter File{1}(43,1)). I change some of the lines and rewrite the file as such
frewind(fileID)
for row=1:length(file{1})
fprintf(fileID,'%s\n',file{1}{row,1});
end
When I reopen the text file it leaves a portion of line 43 in a new line 44
(line 43) There is Ketchup on my hot dog
(line 44) on my hot dog
The rest of the text file is written correctly, what is causing this to happen? even if there is a line 44 generated, if it was blank it would be fine
  댓글 수: 9
Keith Holmlund
Keith Holmlund 2018년 6월 22일
going through it, the following ended up doing the trick
frewind(fileID);
for row=1:size(file{1},1)
fprintf(fileID,'%s\n',file{1}{row,1});
end
dpb
dpb 2018년 6월 22일
Indeed.

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

답변 (1개)

Jan
Jan 2018년 6월 22일
If you overwrite a text file by a shorter string than the original, the remaining characters are not cropped. To reduce the file size, you need an extra tool like FEX: FileResize . You cannot do this in Matlab without recreating the file.
  댓글 수: 1
Walter Roberson
Walter Roberson 2018년 6월 22일
This is the correct answer. MATLAB does not provide any way to make a file shorter. The POSIX standard library defines I/O in the middle of a file as overwriting existing contents without truncating the file unless the user specifically asks for the file to be truncated (an action which there is unfortunately no MATLAB interface for.)

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

카테고리

Help CenterFile Exchange에서 Modeling and Prediction에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by