How to read data from a file into cell array keeping indents undisturbed

조회 수: 4 (최근 30일)
I am trying to read a data from a file, modify it and write to a same file which I did using,
fid = fopen('file.ext','r');
fclose(fid);
lines = textscan(fid,'%s','Delimiter','\n');
...
fid = fopen('file.ext','w');
for row = 1:length(lines{1})
fprintf(fid,'%s\n',lines{1}{row});
end
fclose(fid);
But I could not reproduce the indents which were in the original file. So any suggestions to achieve this and make the above process easier?
Note: the file extension is not .txt but similar to text format. The data which I try to read has html tag elements and attributes.
I would also like to know whether there is any way to directly modify a file without reading it?
Thanks in advance!
  댓글 수: 2
Jan
Jan 2020년 9월 27일
If you close the file by fclose before running textscan, the code should fail with an error message.
Shankar Santhosh
Shankar Santhosh 2020년 9월 28일
You are right! I just misplaced the lines in this query. But I had it right in my code.

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

채택된 답변

Jan
Jan 2020년 9월 27일
편집: Jan 2020년 9월 27일
% Import file:
Str = fileread('file.ext');
% Remove trailing line break to avoid appending an additional empty line:
if ~isempty(Str) && Str(numel(Str)) == char(10)
Str(numel(Str)) = [];
end
% Split lines:
% lines = strsplit(Str, char(10));
% Faster but uglier (this is what happens inside STRSPLIT):
lines = regexp(Str, ['(?:', char(10), ')+'], 'split');
...
% Write output:
fid = fopen('file.ext', 'w');
fprintf(fid, '%s\n', lines{:});
fclose(fid);
  댓글 수: 1
Shankar Santhosh
Shankar Santhosh 2020년 9월 28일
This is exactly what I needed !
Working fine with my scenario. Thanks a lot.
You are great ../\..

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

추가 답변 (1개)

Rik
Rik 2020년 9월 27일
You can get my readfile function from the FEX or through the AddOn-manager (R2017a or later).
It will read a file to a cell array, one cell element per line, and it will preserve all leading and trailing spaces.
One of the advantages of a cell array is that you can trivially write out the modified file: fprintf(fid,'%s\n',txt{:}).
  댓글 수: 3
Rik
Rik 2020년 9월 28일
This is compatible all the way back to Matlab 6.5, and it works on GNU Octave.
Shankar Santhosh
Shankar Santhosh 2020년 9월 28일
Oh Sorry that I misunderstood. This approach also seem to work well.

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

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by