How to sort property -value pair in alphabetical order with Matlab

后端 未结 2 998
名媛妹妹
名媛妹妹 2021-01-22 13:17

I want to add a property-value pair to existing file. In the mean time all the properties should be ordered in alphabetical order. For example :

[Info] % proper         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-22 13:39

    How about read the file into a 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.
    

    Now you have all the data as a struct with properties as fieldnames and values as the field value.

    Now you can update a property simply by:

    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
    

    You can add a property:

    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
    

    You can sort the properties alphabetically using orderfields:

    fileData = orderfields( fileData );
    

    You can write the struct back to file simply using:

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

    Assumptions:

    1. The properties' names are legitimate Matlab field names (see variable naming for details).

    2. The value of each property is always a string.

    3. I did not include any error-checking code in these examples (files not found, wrongly formatted strings, etc.)

    4. I assume the input file is strictly "[prop] val" pairs without any additional comments etc.

提交回复
热议问题