按行处理c文件,并对字符串进行相关处理

1.处理转义字符。

2.查找限定字符之间的内容。

3.查找限制内容中是否包含const关键字,若存在const关键字,判断其后面定义是变量韩式数组,如是变量则在其前添加volatile关键字,若是数组则不进行任何操作。

4.将处理后的内容重新写入文件。

存在问题1.,将文件用\n按行分割,再用join函数使用\n函数重新连接时,会出现写入字符不处理转义字符的情况。

解决1. 使用compose函数对要写入的字符串进行字符转换,成功解决,不处理转义字符的问题。

存在问题2. 处理文件时发现有其他转义字符’\',此时程序认为该字符为转义字符而不是字符。

解决2.若要保留’\‘字符,在每一行内查找’\‘字符,若该行找到’\‘,则将其替换为双’\'即可。

具体代码如下

%按行读取,行内限制添加关键字
clc;
clear all;
prompt = '输入文件夹路径\n';
folderTxt = input(prompt,"s");
fileCInfo = dir([folderTxt '\**\*.c']);
fileHInfo = dir([folderTxt '\**\*.h']);
%fileCInfo = dir('D:\test\**\*.c');
%fileHInfo = dir('D:\test\**\*.h');
fileCLen = length(fileCInfo);
fileHLen = length(fileHInfo);
%处理.C文件
for i = 1 : fileCLen
    % 指定txt文件的路径  
    fileCname =[fileCInfo(i).folder '\' fileCInfo(i).name]
    % 读取txt文件内容 
    fileContents = fileread(fileCname);  
    % 将文件内容按行分割  
    lines = strsplit(fileContents, '\n');

    % 初始化状态变量
    betweenPragmas = false;
    % 遍历每一行  
    for i = 1:length(lines)  
        line = lines{i}; 
        %处理转义字符
        if contains(line, '\') 
            line = strrep(line, '\', '\\');  
        end
            % 检查是否进入或退出#pragma块  
        if contains(line, '#pragma ghs section rodata=".caldata.a1"')  
            betweenPragmas = true;  
        elseif contains(line, '#pragma ghs section rodata=default')  
            betweenPragmas = false;  
        end  

        % % 如果在#pragma块内,检查const关键字,检查这一行是否包含const关键字  
        if betweenPragmas && contains(line, 'const')  
            % 查找const关键字的位置  
            constIdx = strfind(line, 'const');  

            % 如果找到了const,检查它后面是否有数组声明([])  
            if ~isempty(constIdx) && ~contains(line(constIdx + length('const'):end), '[') && ~contains(line(constIdx + length('const'):end), ']')  
               
                % 在const前面插入volatile和空格  
                volatileConst = [line(1:constIdx-1) 'volatile ' 'const ' line(constIdx+length('const'):end)];  
                line = volatileConst;
                
            end  
        end  
        lines{i} = line;
    end  

    % 将修改后的行重新组合成文件内容  
    modifiedContent = join(lines, '\n');
    str = compose(modifiedContent);
    % 将修改后的内容写回文件(如果需要)  
    fileID = fopen(fileCname, 'w');
    if fileID == -1  
        error('无法打开文件。');  
    else
        fprintf(fileID, '%s', str{1});
        disp(['替换后的内容已成功写入文件:', fileCname]);  
    end
    fclose(fileID);
end
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值