Writing in a text file from two different files
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ionut Anghel
le 17 Juin 2015
Réponse apportée : Walter Roberson
le 18 Juin 2015
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 commentaires
Walter Roberson
le 18 Juin 2015
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?
Réponse acceptée
Walter Roberson
le 18 Juin 2015
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Environment and Settings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!