Writing in a text file from two different files

1 次查看(过去 30 天)
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