Writing in a text file from two different files

조회 수: 1 (최근 30일)
Ionut  Anghel
Ionut Anghel 2015년 6월 17일
답변: Walter Roberson 2015년 6월 18일
Hi all; I appologize in advance for easy questions but I'm quite new in using matlab formats .I have 2 files:
myfile01.txt
myfile02.txt
How can I print in myfile03.txt one line from first file followed by a line from the second one. For example:
Myfile01.txt has 100 lines
Myfile02.txt has 1 line
here is the code:
N_lines=100;
fidex_01=fopen('myfile01.txt', 'r');
fidex_02=fopen('myfile02.txt','r');
fidex_03=fopen('myfile03.txt', 'w');
for i=1:10%=N_lines;
read_fidex_01=fgets(fidex_01);
read_fidex_02=fgets(fidex_02);
if feof(fidex_01)
break;
end;
fprintf(fidex_03, '%s', read_fidex_01);
fprintf(fidex_03, '%s', read_fidex_02);
end
  댓글 수: 2
Walter Roberson
Walter Roberson 2015년 6월 18일
Is the output to consist of exactly 2 lines, the first from file 1 and the second from file 2?
Is the output to consist of pairs of lines,
file1 first line
file2 first line
file1 second line
file2 second line
file1 third line
file2 third line
and so on?
Is the output to consist of pairs of lines in which the line from the second file is to be repeated?
file1 first line
file2 first line
file1 second line
file2 first line
file1 third line
file2 first line
and so on?
Ionut  Anghel
Ionut Anghel 2015년 6월 18일
편집: Walter Roberson 2015년 6월 18일
Hi,
Yes. Both ways should be.
I have few cases where the output should be:
file1 first line
file2 first line
file1 second line
file2 second line
file1 third line
file2 third line
and other major part of my work where the output should be:
file1 first line
file2 first line
file1 second line
file2 first line
file1 third line
file2 first line

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

채택된 답변

Walter Roberson
Walter Roberson 2015년 6월 18일
interleave_files = true; %or false. True to use 1,1 2,1 1,2 2,2; false to use 1,1 2,1 1,2 2,1 ...
N_lines=100;
fidex_01=fopen('myfile01.txt', 'r');
fidex_02=fopen('myfile02.txt','r');
fidex_03=fopen('myfile03.txt', 'w');
for i=1:10%=N_lines;
read_fidex_01 = fgets(fidex_01);
if feof(fidex_01); break; end;
%read from second if interleaving or if first time in loop
if interleave_files or i == 1
read_fidex_02 = fgets(fidex_02);
end
fprintf(fidex_03, '%s', read_fidex_01);
fprintf(fidex_03, '%s', read_fidex_02);
end
fclose(fidex_01);
fclose(fidex_02);
fclose(fidex_03);

추가 답변 (0개)

카테고리

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