2

如何读取和写入 ini 文件:我想将新属性添加到现有文件中。我想将 ini 文件写入临时文件,最后将新属性添加到其中。新属性将具有 head、name、desc、value 和 layout(如:第 1 行和第 3 行)

#---------------
# head
# --------------
[name]% type
# desc
value

fileData = [];
fh = fopen( fileName, 'r' ); % read handle
tname=tempname();
wfh =fopen(tname,'w'); % write handle
line = fgetl(fh);
val = '';
Prop ='';
type = '';
header = '';
desc= '';

while ischar(line)

    if strcmpi(line(1),'#') && strcmpi(line(3),'=')
        layout = line(2:end);
    elseif strcmpi(line(1),'#')&& ~strcmpi(line(3),'=')
        header = line(2:end);
    else 
        Prop = regexp(line,{'\[*\w+\]\s*%\s*.*\s*'},'match');
    [property data_type] = strtok(Prop,'%')
    prop_p = property{1};% property_name
    prop_per  = regexprep(prop_p,{'\[','\]'},'');
    prop = prop_per{1};
    Dtype = data_type{1}; % datatype
    dtype = strtrim(strrep(Dtype,'%',''));
    DATA_type = dtype{1};

end 



 % How can i define filedname (prop) for the 'layout' and 'header' as they are found in lines before the actual'prop'.

  % From command window

  % Undefined variable prop.

  % Error in ecco2511>add (line 212)
  % fileData.(prop{1}).layout = layout;


    desc = fgetl(fh); % description
    desc = desc(1:end);
    line = fgetl(fh);
    val = line(1:end);

    fileData.(prop).layout = layout;
    fileData.(prop).header = header;
    fileData.(prop).type = DATA_type;
    fileData.(prop).desc = desc;
    fileData.(prop).val = val;

    line = fgetl(fh); % keep reading

end

if ~isfield( fileData, propName)
    fileData.(propName).val = newVal;
    fileData.(propName).type = datatype;
    fileData.(propName).desc = description;
    fileData.(propName).layout = layout;
    fileData.(propName).header = header;

else
    error ( 'property %s already exists, use set to change its value',propName );
end

fileData = orderfields( fileData );
propNames = fieldnames( fileData );

for ii = 1:numel( propNames )

    fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
    fprintf(wfh,'\n');
    fprintf(wfh,'%s\r',fileData.(propNames{ii}).header);
    fprintf(wfh,'\n');
    fprintf(wfh,'%s\r',fileData.(propNames{ii}).layout);
    fprintf(wfh,'\n');
    fprintf( wfh, '[%s]%s\r', (propNames{ii}),fileData.(propNames{ii}).type);
    fprintf(wfh,'\n');
    fprintf( wfh,'#%s\r',fileData.(propNames{ii}).desc);
    fprintf(wfh,'\n');
    fprintf( wfh,'%s\r',fileData.(propNames{ii}).val);
    fprintf(wfh,'\n');
end
fclose(fh);
fclose(wfh);
[status,errmsg]= movefile(tname,fileName,'f');
4

1 回答 1

1

听起来您需要来自 MATLAB File Exchange 的INI Config 。它将允许您读取、写入和修改 INI 样式文件。我已经使用了很多次,而且效果很好。

于 2013-05-13T04:23:07.340 回答