필터 지우기
필터 지우기

fopen and fget reading lines from a text

조회 수: 2 (최근 30일)
Sergio
Sergio 2024년 2월 2일
댓글: Stephen23 2024년 2월 2일
Hi, I try to work with fget and fopen, and I would like to read the first three lines from a text file (attached), and print them on the MATLAB output,
I try
fid = fopen('test.txt');
line_ex = fgetl(5) % read line excluding newline character
fid = fopen('test.txt');
line_ex = fgetl(5) % read line excluding newline character
fid = fopen('test.txt');
line_ex = fgetl(5) % read line excluding newline character
However, this prints out only the three first lines one time, then it continues to 4,5,6, then 7,8,9 etc.
Is there a better way to simply reproduce the three first lines of the text files, with the same command, over again?
Thanks

채택된 답변

Dyuman Joshi
Dyuman Joshi 2024년 2월 2일
편집: Dyuman Joshi 2024년 2월 2일
You need to use the file ID as input to fgetl -
fid = fopen('test.txt');
%lines to read
num = 3;
%Preallocate a cell array to store the data
C = cell(num,1);
for k=1:num
%Read the line
str = fgetl(fid);
%Store it in a cell element
C{k} = str;
%Display it
disp(str)
end
X-412.538 Y-150.417 Z505.02 B21=-24.976 A1=19.761 C0. X-412.313 Y-151.044 Z505.02 B21=-24.98 A1=19.85 C0. X-412.087 Y-151.67 Z505.02 B21=-24.984 A1=19.938 C0.
C
C = 3×1 cell array
{'X-412.538 Y-150.417 Z505.02 B21=-24.976 A1=19.761 C0.'} {'X-412.313 Y-151.044 Z505.02 B21=-24.98 A1=19.85 C0.' } {'X-412.087 Y-151.67 Z505.02 B21=-24.984 A1=19.938 C0.' }
  댓글 수: 3
Dyuman Joshi
Dyuman Joshi 2024년 2월 2일
Okay.
But it's not a good idea to hard code values. Better to store it as a variable and use it accordingly.
Stephen23
Stephen23 2024년 2월 2일
"that File ID was given as 5"
Do not hard-code the File ID.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by