필터 지우기
필터 지우기

merging files using for loop

조회 수: 2 (최근 30일)
MF
MF 2016년 3월 18일
댓글: MF 2016년 3월 19일
I am trying to merge 7 text files into 1 using system ('copy 090615.txt+090616.txt+090617.txt+090618.txt+090619.txt+090619.txt+090620.txt+090621.txt New.txt'); How can I do the same thing using a for loop. Thanks

채택된 답변

Ced
Ced 2016년 3월 19일
편집: Ced 2016년 3월 19일
The above method should work.
However, instead of copying the content into a string ( which might be HUGE for several files ), try using the flag 'a' (append) instead of 'w' (write, will start at the beginning of the file again) when opening the file, i.e.
fid = fopen(newFile, 'a');
This way, you can read the files one at a time, and write the content to a single file.
PS: If the file is not empty in the beginning, but you don't want to keep the old content, you need to open it with "w" for k == 1, and then use "a".
  댓글 수: 1
MF
MF 2016년 3월 19일
It's working. Thank you very much

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

추가 답변 (1개)

Jan
Jan 2016년 3월 19일
편집: Jan 2016년 3월 19일
Calling the operating system is indirect. You can do this inside Matlab instead:
Folder = cd; % Set accordingly
Str = '';
for k = 90615:90621
FileName = fullfile(Folder, sprintf('%06d.txt', k));
Str = [Str, fileread(FileName)];
end
newFile = fullfile(Folder, 'New.txt');
fid = fopen(newFile, 'w');
if fid == -1, error('Cannot open file for writing: %s', newFile);
fwrite(fid, Str, 'char');
fclose(fid);
  댓글 수: 1
MF
MF 2016년 3월 19일
but still the file created remains empty. I want the content of all files to be saved into a single file, in this case the new file. Thanks

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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by