Concatenate data using fgets

조회 수: 17 (최근 30일)
Zhonghao Liao
Zhonghao Liao 2016년 9월 29일
댓글: Zhonghao Liao 2016년 9월 29일
I want to read a data pattern from a txt file and concatenate each line together. I wrote the following program but the error message shows:
function read_datapattern(filename)
fid = fopen(filename,'rt');
if fid < 0
error('error opening file %s\n\n',filename);
end
pattern = fgets(fid);
for n = 1:32767
nextline = fgets(fid);
pattern = strcat(pattern, nextline);
fprintf(pattern);
fprintf('\n');
fclose(fid);
end
"Invalid file identifier. Use fopen to generate a valid file identifier." "nextline = fgets(fid);"
How do I need to modify the program? Thank you~

채택된 답변

KSSV
KSSV 2016년 9월 29일
편집: KSSV 2016년 9월 29일
You are closing the file in the loop. close the file after the loop. I assume the below should work.
function read_datapattern(filename)
fid = fopen(filename,'rt');
if fid < 0
error('error opening file %s\n\n',filename);
end
pattern = fgets(fid);
for n = 1:32767
nextline = fgets(fid);
pattern = strcat(pattern, nextline);
fprintf(pattern);
fprintf('\n');
end
fclose(fid);
  댓글 수: 1
Zhonghao Liao
Zhonghao Liao 2016년 9월 29일
Yes, that is work. Thank you~

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

추가 답변 (0개)

카테고리

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