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
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?
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!