How do you add a line to the beginning of a .txt file?

18 visualizaciones (últimos 30 días)
klf
klf el 27 de Jun. de 2012
I have some .txt files that contain rectangular matrices, and I would like to add one line to the beginning of each .txt file that contains a single number. E.g., I have a .txt file that contains:
1 2 3 4
5 6 7 8
9 10 11 12
And I would like to create a new .txt file that looks exactly the same, except with a new first row added to it, and with a single number in that row. E.g.:
20
1 2 3 4
5 6 7 8
9 10 11 12
Help? I think this has something to do with fprintf, but I don't know how to use it.

Respuestas (1)

Walter Roberson
Walter Roberson el 27 de Jun. de 2012
It is difficult to add text inside a text file. The easiest thing to do is to create a new text file and output everything to it, copying from the original file.
infid = fopen('YourFile.txt', 'rt');
outfid = fopen('YourNewFile.txt', 'wt');
fprintf( outfid, '20\n' ); %the text you are adding at the beginning
while true
thisline = fgetl(infid); %read line from input file
if ~ischar(thisline); break; end %reached end of file
fprintf( outfid, '%s\n', thisline ); %write the line to the output file
end
fclose(infid);
fclose(outfid);

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by