Ini文件读写+添加新属性+ matlab

时间:2013-05-13 00:57:33

标签: matlab

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

#---------------
 #head
 #--------------
 [名称]%类型
 #desc
 值

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');

1 个答案:

答案 0 :(得分:1)

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