How do you add a line to the beginning of a .txt file?
18 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
Walter Roberson
on 27 Jun 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);
0 Comments
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!