MATLAB解析和保存ini文件

1. 将ini文件转换成struct结构体

function data = ini2struct(filename)
    fid = fopen(filename, 'r');

    if fid == -1
        error('Unable to open file %s.', filename);
    end

    data = struct();
    section = '';

    while ~feof(fid)
        line = fgetl(fid);
        line = strtrim(line);

        % 如果是注释行或者空行,则继续下一次循环
        if isempty(line) || line(1) == ';' || line(1) == '#'
            continue;
        end

        % 如果是节标题
        if line(1) == '[' && line(end) == ']'
            section = line(2:end-1);
            data.(section) = struct();
            continue;
        end

        % 解析键值对
        equalIndex = strfind(line, '=');
        if isempty(equalIndex)
            error('Invalid format in file %s.', filename);
        end

        key = strtrim(line(1:equalIndex-1));
        value = strtrim(line(equalIndex+1:end));
        data.(section).(key) = value;
    end

    fclose(fid);
end

2. 将结构体保存为ini文件

function struct2ini(data, filename)
    fid = fopen(filename, 'w');

    if fid == -1
        error('Unable to open file %s.', filename);
    end

    fields = fieldnames(data);

    for i = 1:numel(fields)
        section = fields{i};
        keys = fieldnames(data.(section));

        fprintf(fid, '[%s]\n', section);

        for j = 1:numel(keys)
            key = keys{j};
            value = data.(section).(key);
            fprintf(fid, '%s=%s\n', key, value);
        end

        fprintf(fid, '\n');
    end

    fclose(fid);
end

3. 读取ini文件时的转换

INI文件中的值都被视为字符串,如果需要将值解析为其他类型(如浮点数或数组),需要在代码中进行转换:

data = ini2struct('test.ini');

% 从结构体中获取对应的值
robotValue = data.Robot;
limitAValue = str2num(data.Limit.A); % 将字符串转换为数值
limitBValue = str2num(data.Limit.B); % 将字符串转换为数值

% 打印结果
disp(['Robot: ' robotValue]);
disp(['Limit A: ' num2str(limitAValue)]);
disp(['Limit B: ' num2str(limitBValue)]);

你可能感兴趣的:(#,▶,MATLAB/Simulink,matlab,ini)