How can I prepend text to a file using MATLAB?

7 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 20 Jan 2010
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);

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!