プロパティと値のペアを既存のファイルに追加したいと考えています。それまでの間、すべてのプロパティをアルファベット順に並べる必要があります。例えば :
[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