How can I prepend text to a file using MATLAB?
7 次查看(过去 30 天)
显示 更早的评论
I would like to insert new text at the beginning of a file using MATLAB. Is there a function that will do this for me?
采纳的回答
MathWorks Support Team
2010-1-20
While we do not have any built-in routines in our products to do specifically what you want, you may be able to write a MATLAB function that does this.
You will need to do something along the lines of the following:
1. Open a temporary file (see "doc tempname")
2. Write your data there that you wish to prepend
3. Open your original file for reading
4. Read from your original and write to the temporary file
5. Close both files
6. Copy the temporary over the original (see "doc copyfile")
An example is shown below.
function prepend2file( string, filename, newline )
% newline: is an optional boolean, that if true will append a \n to the end
% of the string that is sent in such that the original text starts on the
% next line rather than the end of the line that the string is on
% string: a single line string
% filename: the file you want to prepend to
tempFile = tempname
fw = fopen( tempFile, 'wt' );
if nargin < 3
newline = false;
end
if newline
fwrite( fw, sprintf('%s\n', string ) );
else
fwrite( fw, string );
end
fclose( fw );
appendFiles( filename, tempFile );
copyfile( tempFile, filename );
delete(tempFile);
% append readFile to writtenFile
function status = appendFiles( readFile, writtenFile )
fr = fopen( readFile, 'rt' );
fw = fopen( writtenFile, 'at' );
while feof( fr ) == 0
tline = fgetl( fr );
fwrite( fw, sprintf('%s\n',tline ) );
end
fclose(fr);
fclose(fw);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call C from MATLAB 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!