Borrar filtros
Borrar filtros

Writing in a text file from two different files

1 visualización (últimos 30 días)
Ionut  Anghel
Ionut Anghel el 17 de Jun. de 2015
Respondida: Walter Roberson el 18 de Jun. de 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 comentarios
Walter Roberson
Walter Roberson el 18 de Jun. de 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?
Ionut  Anghel
Ionut Anghel el 18 de Jun. de 2015
Editada: Walter Roberson el 18 de Jun. de 2015
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

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 18 de Jun. de 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);

Más respuestas (0)

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by