我想将属性 - 值对添加到现有文件中。同时,所有属性都应按字母顺序排序。例如:
[Info] % property 1
value 1
[system] % property 2
value 2
如何添加其他属性,以便按字母顺序对所有属性进行排序。我能够使用属性值对添加到文件的末尾
fh = fopen(filename,'a')
但我无法按字母顺序排序。
到目前为止,我尝试了如下,但是使用这个,它只保持打印新的属性 - 值对。我想打印剩余的属性,然后打印新的属性。
function [] = myfun(filename ,propName,propvalue)
rfh = fopen(filename,'r');
tname = tempname();
wfh = fopen(tname,'w');
line = fgetl(rfh);
while ischar(line)
if (line(1) == '[') && (line(end) == ']')
property = lower(line(2:end-1)) % from ini file
String2 = property;
String1 = propName;
[sat] = sor(String1,String2)% subfunction
if sat == -1
fprintf(wfh,'[%s]\r\n%s\r\n',propName,propvalue);
else
fprintf(wfh,'%s\r\n',line);
end
else
fprintf(wfh,'%s\r\n',line);
end
line = fgetl(rfh);
end
fclose(rfh);
fclose(wfh);
movefile(tname,filename,'f')
function [sat] = sor(String1,String2)
Index = 1;
while Index < length(String1) && Index < length(String2) && String1(Index) == String2(Index)
Index = Index + 1;
end
% Return the appropriate code
if String1(Index) < String2(Index)
sat= -1
elseif String1(Index) > String2(Index)
sat= +1
else % the characters at this position are equal -- the shorter of the two strings should be "less than"
if length(String1) == length(String2)
sat = 0
elseif length(String1) < length(String2)
sat = -1
else
sat = +1
end
end
答案 0 :(得分:3)
这是.ini
个文件吗?您可能需要查看MATLAB文件交换中的INIConfig,这是一组用于处理在方便的类中排列的INI文件的例程。我没有用它,但也许它可以做你需要的。
如果没有,您可以随时:
[
开头的行后跟一个字母,而不是您要插入的属性,请插入您的属性和值答案 1 :(得分:1)
如何将文件读入struct
?
function fileData = readFileIntoStruct( fileName )
%
% read [property] value pairs file into struct
%
fh = fopen( fileName, 'r' ); % read handle
line = fgetl( fh );
while ischar( line )
% property
tkn = regexp( line, '\[([^\]+)]\]', 'once', 'tokens' );
% read next line for value
val = fgetl( fh );
fileDate.(tkn{1}) = val;
line = fgetl( fh ); % keep reading
end
fclose( fh ); % don't forget to close the file at the end.
现在,您将所有数据都设为struct
,其属性为fieldnames
,值为field
值。
现在您只需通过以下方式更新属性:
function fileData = updateProperty( fileData, propName, newVal )
if isfield( fileData, propName )
fileData.(propName) = newVal;
else
warning( 'property %s does not exist - please add it first', propName );
end
您可以添加属性:
function fileData = addProperty( fileData, propName, newVal )
if ~isfield( fileData, propName )
fileData.(propName) = newVal;
else
warning ( 'property %s already exists, use update to change its value', propName );
end
您可以使用orderfields
按字母顺序对属性进行排序:
fileData = orderfields( fileData );
您只需使用以下命令将struct
写回文件:
function writeDataToFile( newFileName, fileData )
fopen( newFileName , 'w' ); %write handle
propNames = fieldnames( fileData );
for ii = 1:numel( propNames )
fprintf( fh, '[%s]\r\n%s\r\n', propNames{ii}, fileData.(propNames{ii}) );
end
fclose( fh );
<强>假设:强>
属性的名称是合法的Matlab字段名称(详见变量命名)。
每个属性的值始终为字符串。
我没有在这些示例中包含任何错误检查代码(找不到文件,格式错误的字符串等)
我假设输入文件是严格的“[prop] val”对而没有任何其他评论等。