📄 inifile.m
字号:
function varargout = inifile(varargin)
%INIFILE Creates, reads, or writes data from/to a standard ini (ascii)
% file. Such a file is organized into sections
% ([section name]), subsections(enclosed by {subsection name}),
% and keys (key=value). Empty lines and lines with the first non-empty
% character being ; (comment lines) are ignored.
%
% Usage:
% INIFILE(fileName,'new')
% Rewrites an existing file - creates a new, empty file.
%
% INIFILE(fileName,'write',keys,<style>)
% Writes keys given as cell array of strings (see description of
% the keys below). Optional style variable: 'tabbed' writes sections,
% subsections and keys in a tabbed style to get more readable
% file. The 'plain' style is the default style. This only affects
% the keys that will be written/rewritten.
%
% INIFILE(fileName,'deletekeys',keys)
% Deletes keys and their values - if they exist.
%
% [readsett,result] = INIFILE(fileName,'read',keys)
% Reads the values of the keys where readsett is a cell array of
% strings and/or numeric values of the keys. If any of the keys
% is not found, the default value is returned (if given in the
% 5-th column of the keys parameter). result is a cell array of
% strings - one for each key read; empty if OK, error/warning
% string if error; in both cases an empty string is returned in
% readsett{i} for the i-th key if error.
%
% [keys,sections,subsections] = INIFILE(fName,'readall')
% Reads entire file and returns all the sections, subsections
% and keys found.
%
%
% Notes on the keys cell array given as an input parameter:
% Cell array of STRINGS; either 3, 4, or 5 columns.
% Each row has the same number of columns. The columns are:
% 'section': section name string (the root is considered if
% empty)
% 'subsection': subsection name string (the root is considered
% if empty)
% 'key': name of the field to write/read from (given as
% a string).
% value: (optional) STRING or NUMERIC value (scalar or
% matrix) to be written to the
% ini file in the case of 'write' operation OR
% conversion CHAR for read operation:
% 'i' for integer, 'd' for double, 's' or
% '' or not given for string (default).
% defaultValue: (optional) string or numeric value (scalar or
% matrix) that is returned when the key is not
% found or an empty value is found
% when reading ('read' operation).
% If the defaultValue is not given and the key
% is not found, an empty value is returned.
% It MUST be in the format as given by the
% value, e.g. if the value = 'i' it must be
% given as an integer etc.
%
%
% EXAMPLE:
% Suppose we want a new ini file, test1.ini with 4 fields, including a
% 5x5 matrix (see below). We can write the 5 fields into the ini file
% using:
%
% x = rand(5); % matrix data
% inifile('test1.ini','new');
% writeKeys = {'measurement','person','name','Primoz Cermelj';...
% 'measurement','protocol','id',1;...
% 'application','','description.m1','some...';...
% 'application','','description.m2','some...';...
% 'data','','x',x};
% inifile('test1.ini','write',writeKeys,'plain');
%
% Later, you can read them out. Additionally, if any of them won't
% exist, a default value will be returned (if the 5-th column is given
% for all the rows as below).
%
% readKeys = {'measurement','person','name','','John Doe';...
% 'measurement','protocol','id','i',0;...
% 'application','','description.m1','','none';...
% 'application','','description.m2','','none';...
% 'data','','x','d',zeros(5)};
% readSett = inifile('test1.ini','read',readKeys);
%
% Or, we can just read all the keys out
% [keys,sections,subsections] = inifile(test1.ini,'readall');
%
%
% NOTES: If the operation is 'write' and the file is empty or does not
% exist, a new file is created. When writing and if any of the section
% or subsection or key does not exist, it creates (adds) a new one.
% Everything but value is NOT case sensitive. Given keys and values
% will be trimmed (leading and trailing spaces will be removed).
% Any duplicates (section, subsection, and keys) are ignored. Empty
% section and/or subsection can be given as an empty string, '',
% but NOT as an empty matrix, [].
%
% Numeric matrices can be represented as strings in one of the two form:
% '1 2 3;4 5 6' or '1,2,3;4,5,6' (an example).
%
% Comment lines starts with ; as the first non-empty character but
% comments can not exist as a tail to a standard, non-comment line as ;
% is also used as a row delimiter for matrices.
%
% This function was tested on the win32 platform only but it should
% also work on Unix/Linux platforms. Since some short-circuit operators
% are used, at least Matlab 6.5 (R13) is required.
%
%
% FREE SOFTWARE - please refer the source
% Copyright (c) 2003-2005 by Primoz Cermelj
% First release on 29.01.2003
% Primoz Cermelj, Slovenia
% Contact: primoz.cermelj@email.si
% Download location: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=2976&objectType=file
%
% Version: 1.4.2
% Last revision: 12.01.2007
%
% Bug reports, questions, etc. can be sent to the e-mail given above.
%
% This programme is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This programme is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% ACKNOWLEDGEMENTS: Thanks to Diego De Rosa for a suggestion/fix how to
% read the value when the key is found but empty.
%--------------------------------------------------------------------------
%----------------
% INIFILE history
%----------------
%
% [v.1.4.2] 12.01.2007
% - FIX: When in read mode and a certain key is found but the value is
% empty, the default value will be used instead.
%
% [v.1.4.1] 12.01.2006
% - FIX: Some minor refinements (speed,...)
%
% [v.1.4.0] 05.12.2006
% - NEW: New 'readall' option added which reads all the sections,
% subsections and keys out
%
% [v.1.3.2 - v.1.3.5] 25.08.2004
% - NEW: Speed improvement for large files - using fread and fwrite instead
% of fscanf and fprintf, respectively
% - NEW: Some minor changes
% - NEW: Writing speed-up
% - NEW: New-line chars are properly set for pc, unix, and mac
%
% [v.1.3.1] 04.05.2004
% - NEW: Comment lines are detected and thus ignored; comment lines are
% lines with first non-empty character being ;
% - NEW: Lines not belonging to any of the recognized types (key, section,
% comment,...) raise an error.
%
% [v.1.3.0] 21.04.2004
% - NEW: 2D Numeric matrices can be read/written
% - FIX: Bug related to read operation and default value has been removed
%
% [v.1.2.0] 30.04.2004
% - NEW: Automatic conversion capability (integers, doubles, and strings)
% added for read and write operations
%
% [v.1.1.0] 04.02.2004
% - FIX: 'writetext' option removed (there was a bug previously)
%
% [v.1.01b] 19.12.2003
% - NEW: A new concept - multiple keys can now be read, written, or deleted
% ALL AT ONCE which makes this function much faster. For example, to
% write 1000 keys, using previous versions it took 157 seconds on a
% 1.5 GHz machine, with this new version it took only 0.9 seconds.
% In general, the speed improvement is greater when a larger number of
% read/written keys is considered (with respect to the older version).
% - NEW: The format of the input parameters has changed. See above.
%
% [v.0.97] 19.11.2003
% - NEW: Additional m-function, strtrim, is no longer needed
%
% [v.0.96] 16.10.2003
% - FIX: Detects empty keys
%
% [v.0.95] 04.07.2003
% - NEW: 'deletekey' option/operation added
% - FIX: A major file refinement to obtain a more compact utility ->
% additional operations can "easily" be implemented
%
% [v.0.91-0.94]
% - FIX: Some minor refinements
%
% [v.0.90] 29.01.2003
% - NEW: First release of this tool
%
%----------------
global NL_CHAR;
% Checks the input arguments
if nargin == 0
disp('INIFILE v1.4.1');
disp('Copyright (c) 2003-2005 by Primoz Cermelj');
disp('This is FREE SOFTWARE');
disp('Type <help inifile> to get more help on its usage');
return
elseif nargin < 2
error('Not enough input arguments');
end
fileName = varargin{1};
operation = varargin{2};
if (strcmpi(operation,'read')) | (strcmpi(operation,'deletekeys'))
if nargin < 3
error('Not enough input arguments.');
end
if ~exist(fileName)
error(['File ' fileName ' does not exist.']);
end
keys = varargin{3};
[m,n] = size(keys);
if n < 3
error('Keys argument must have at least 3 columns for read operation');
end
for ii=1:m
if isempty(keys(ii,3)) | ~ischar(keys{ii,3})
error('Empty or non-char keys are not allowed.');
end
end
elseif (strcmpi(operation,'write'))
if nargin < 3
error('Not enough input arguments');
end
keys = varargin{3};
if nargin < 4 || isempty(varargin{4})
style = 'plain';
else
style = varargin{4};
if ~(strcmpi(style,'plain') | strcmpi(style,'tabbed')) | ~ischar(style)
error('Unsupported style given or style not given as a string');
end
end
[m,n] = size(keys);
if n < 4
error('Keys argument requires 4 columns for write operation');
end
for ii=1:m
if isempty(keys(ii,3)) | ~ischar(keys{ii,3})
error('Empty or non-char keys are not allowed.');
end
end
elseif (strcmpi(operation,'readall'))
%
elseif (~strcmpi(operation,'new'))
error(['Unknown inifile operation: ''' operation '''']);
end
if nargin >= 3
for ii=1:m
for jj=1:3
if ~ischar(keys{ii,jj})
error('All cells from the first 3 columns must be given as strings, even the empty ones.');
end
end
end
end
% Sets the new-line character/string
if ispc
NL_CHAR = '\r\n';
elseif isunix
NL_CHAR = '\n';
else
NL_CHAR = '\r';
end
readsett = [];
result = [];
%----------------------------
% CREATES a new, empty file (rewrites an existing one)
%----------------------------
if strcmpi(operation,'new')
fh = fopen(fileName,'w');
if fh == -1
error(['File: ''' fileName ''' can not be (re)created']);
end
fclose(fh);
return
%----------------------------
% READS the whole data (all keys)
%----------------------------
elseif (strcmpi(operation,'readall'))
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -