How do you add a line to the beginning of a .txt file?
19 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Walter Roberson
2012-6-27
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 个评论
另请参阅
类别
在 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!