How to read input.txt?

조회 수: 7 (최근 30일)
Yasuyuki Hamanaka
Yasuyuki Hamanaka 2021년 8월 24일
댓글: Walter Roberson 2021년 8월 25일
Hello!
Would you tell me how to read .txt file like below.
aaaaaa
bbbbbb
1
200
2000
4129
4189
I would like to read first two lines as string and other lines as real.
I tried to use fscanf though, it doesn't work well.
Thank you.
  댓글 수: 3
Yasuyuki Hamanaka
Yasuyuki Hamanaka 2021년 8월 24일
I made mistake. I edited it. Thank you.
Stephen23
Stephen23 2021년 8월 24일
@Yasuyuki Hamanaka: what integer do you expect the characters 'aaaaaa' to return ?

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

채택된 답변

Walter Roberson
Walter Roberson 2021년 8월 24일
fid = fopen('input.txt');
textlines{1} = fgetl(fid);
textlines{2} = fgetl(fid);
numbers = cell2mat(textscan(fid, '%f'));
fclose(fid)
  댓글 수: 2
Yasuyuki Hamanaka
Yasuyuki Hamanaka 2021년 8월 25일
What I want to know seems to be function fgetl. I appreciate you.
Walter Roberson
Walter Roberson 2021년 8월 25일
For future reference:
There is also the closely related function fgets() . The difference between fgetl() and fgets() is that fgetl() strips the line terminators off, but fgets() leaves them in.
So when the purpose is to copy a file, then fgets() is better because it includes the original line terminators in -- if the original line terminator was CR+LF then the CR+LF will both be present for fgets() and will make it into any file that you write them to fgetl() would remove the CR+LF, so fgetl() is better for the case where you are analyzing the content and don't want to have to worry all the time about whether the original had CR+LF or LF alone.

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

추가 답변 (1개)

dpb
dpb 2021년 8월 24일
Are the string data pertinent or just in the way of returning the numeric data?
If the former, while you can make it work with low-level i/o such as fprintf, it's the hard way to go at it -- use
readcell instead.
If the latter and the text is (say) a header line and units or similar, use readtable

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by