Reading a multi line string into a single string

조회 수: 9 (최근 30일)
Justin
Justin 2011년 3월 19일
I have opened a file with a string consisting of three lines. I want to read these lines from the file and store them in my "template" variable as a three line string. All I can get is the last line of the string to be stored in "template"
while feof(fid) == 0;
line = fgets(fid);
template = strvcat(line)
end
Thanks for the help

채택된 답변

Jan
Jan 2011년 3월 19일
template = {};
while feof(fid) == 0;
template{end + 1} = fgets(fid);
end
templateChar = char(template);
More efficient:
C = textscan(fid, '%s', 'delimiter', '\n');
templateChar = char(C{1});
EDITED: textread -> textscan (Thanks, Jiro!)
  댓글 수: 1
Jiro Doke
Jiro Doke 2011년 3월 20일
@Jan, I think you meant to use "textscan", not "textread". "textread" requires the first input to be the actual file name, not the output of fopen. And "textscan" is preferred anyway.

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

추가 답변 (1개)

Matt Tearle
Matt Tearle 2011년 3월 19일
You can read the whole contents of a file using fileread. Then use regexp to mess with it -- eg, split on "\n"

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by