Append data at the beginning of a file MATLAB

37 views (last 30 days)
Hi, please how can fopen be used to append data at the beginning of the file ? like a header.
thank-you

Accepted Answer

Jan
Jan on 28 Jun 2013
Edited: Jan on 28 Jun 2013
You cannot insert characters in front of a file directly. This is a limitation of the file systems and not a problem of Matlab and not a task for FOPEN. So you have to read the complete file at first, add the new characters in the memory and (over)write a new file:
S = fileread(FileName);
S = ['Your header line', char(10), S];
FID = fopen(FileName, 'w');
if FID == -1, error('Cannot open file %s', FileName); end
fwrite(FID, S, 'char');
fclose(FID);
There should be an equivalent process using a memory mapped file. I'm not sure if internally exactly the same is performed, such that there is no difference is the speed. But I assume if the files contains several GigaBytes, the memory mapped method should be better.

More Answers (2)

Siamak Layeghy
Siamak Layeghy on 7 Dec 2018
'w'
Open or create new file for writing. Discard existing contents, if any.
It does not append it discards existing data.
  1 Comment
Walter Roberson
Walter Roberson on 7 Dec 2018
Edited: Walter Roberson on 30 Oct 2020
yes but Jan does fileread() first so the complete contents are already in memory. As the entire file needs to be overwritten from the beginning it makes more sense to use w access than to use a+ access on the fopen followed immediately by fseek to the beginning since a+ positions by default to the end. Using a access would not permit positioning to the beginning to rewrite from there.
You have been misled by the wording of the question . "Appending" at the beginning involves inserting at the beginning not just adding more at the end of file.

Sign in to comment.


fhz
fhz on 25 Nov 2019
Hi Octavio.
You may check the function fc_lib_file_add_header_to_file, from my File Manipulation Library at:
I paste below the function. It receives the name of file and its extension and the optional argument of the string you want to insert. If no optional argument, the the function loads my predefined header, which writes the name of the file and the date of today on it. The string is written with the command "char" for each newline on it.
Maybe I will insert an option to delete or not the temporary file created in the process.
%% algorithm
function fc_lib_file_add_header_to_file(file_name, str_ext, varargin)
%% varargin analysis
if nargin == 2
header = fc_header(file_name);
else
header = char(varargin{1});
end
%% main
file_name_ext = [file_name,str_ext];
tmp_file_ext = sprintf('tmp_file.%s', str_ext);
copyfile(file_name_ext, tmp_file_ext);
fid = fopen(file_name_ext,'w');
%% insert header at the top of the original file
% based on: save_file_tex from this same library
[l, c] = size(header);
for i = 1:l
buffer = header(i,:);
for j = c:-1:1
if buffer(j) == ' '
buffer(j) = '';
else
break;
end
end
fprintf(fid, '%s\n', buffer);
end
%% insert the copied tmp_file_ext into the original file
fid_tmp = fopen(tmp_file_ext,'r');
while 1
% === pega uma linha do arquivo - get a file line
tline = fgetl(fid_tmp);
% === criterio de saida quando nao encontra mais linha - exit criterium and do not find a line
if ~ischar(tline)
break;
end
fprintf(fid, '%s\n', tline);
end
%% close files and delete tmp_file_ext
fclose(fid);
fclose(fid_tmp);
delete(tmp_file_ext);
end
%% function to alocate my predefined header
function str = fc_header(file_name)
% insert today as date of creation
dh = clock; ano = dh(1); mes = dh(2); dia = dh(3);
s = sprintf('%g.%g.%g',dia,mes,ano);
% predefined header
str = char(...
sprintf('%%%% %s', file_name),...
'%%%%%%%%%%%%%',...
sprintf('%% help %s', file_name),...
'% Belongs to private library',...
'%%%%%%%%%%%%%',...
'% Author: M.Eng. Fernando Henrique G. Zucatelli (UFABC)',...
'% COPYRIGHT: Free for non evil use. (Não use este código para o mal)',...
'%%%%%%%%%%%%%',...
'% Description of the function',...
'%%%%%%%%%%%%%',...
'% Source: Link the source material when it is avaliable',...
'%%%%%%%%%%%%%',...
sprintf('%% version 01: %s -- Creation', s),...
'% Some details of this version',...
'% The numbers are in the "%02d" format and separate with colon ":"',...
'% Each version must have the date in the format dd.mm.yyyy',...
'%%%%%%%%%%%%% Example 01',...
'% Examples must call the function and may call other related functions',...
'%%%%%%%%%%%%%',...
'%% algorithm');
end

Categories

Find more on File Operations 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!