You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用MATLAB/Simulink的.m脚本迁移多文件夹自动生成的.c和.h文件

用MATLAB脚本批量移动分散的.c/.h文件到指定文件夹

Got it,我来给你一套实用的MATLAB脚本方案,专门解决这种分散在不同文件夹里的.c/.h文件批量归集的需求,步骤清晰还能处理重名文件避免覆盖:

核心思路

先定义目标文件夹和要搜索的源文件夹范围,递归找出所有.c和.h文件,然后逐个移动到目标文件夹,同时处理可能的重名问题。

完整可运行脚本

% ---------------------- 配置参数 ----------------------
targetFolder = 'D:\MyUnifiedCodeFolder'; % 替换成你要统一存放的目标文件夹路径
sourceRootFolder = 'D:\MySourceParentDir'; % 替换成包含所有子文件夹的父目录
% 如果你有多个独立的源文件夹,改成数组形式:sourceRootFolder = {'D:\Folder1', 'D:\Folder2', 'D:\Folder3'};

% 自动创建目标文件夹(如果不存在)
if ~exist(targetFolder, 'dir')
    mkdir(targetFolder);
    fprintf('已创建目标文件夹:%s\n', targetFolder);
end

% ---------------------- 搜索所有目标文件 ----------------------
fileList = [];
% 处理单个源文件夹或多个源文件夹的情况
if ischar(sourceRootFolder)
    % 递归搜索当前文件夹及所有子文件夹下的.c和.h
    temp_c = dir(fullfile(sourceRootFolder, '**', '*.c'));
    temp_h = dir(fullfile(sourceRootFolder, '**', '*.h'));
    fileList = [fileList; temp_c; temp_h];
elseif iscell(sourceRootFolder)
    % 遍历多个独立源文件夹
    for idx = 1:length(sourceRootFolder)
        temp_c = dir(fullfile(sourceRootFolder{idx}, '**', '*.c'));
        temp_h = dir(fullfile(sourceRootFolder{idx}, '**', '*.h'));
        fileList = [fileList; temp_c; temp_h];
    end
end

if isempty(fileList)
    fprintf('未找到任何.c或.h文件!\n');
    return;
end
fprintf('共找到 %d 个待移动文件\n', length(fileList));

% ---------------------- 批量移动文件 ----------------------
for i = 1:length(fileList)
    % 获取当前文件的完整源路径
    sourceFullPath = fullfile(fileList(i).folder, fileList(i).name);
    % 初始目标路径
    targetFullPath = fullfile(targetFolder, fileList(i).name);
    
    % 处理重名文件:如果目标路径已存在,自动添加序号后缀
    counter = 1;
    while exist(targetFullPath, 'file')
        [~, fileName, fileExt] = fileparts(fileList(i).name);
        newFileName = sprintf('%s_%d%s', fileName, counter, fileExt);
        targetFullPath = fullfile(targetFolder, newFileName);
        counter = counter + 1;
    end
    
    % 执行移动操作
    movefile(sourceFullPath, targetFullPath);
    fprintf('已移动:%s -> %s\n', sourceFullPath, targetFullPath);
end

fprintf('所有文件移动完成!\n');

关键细节说明

  • 递归搜索:脚本里的**是MATLAB的递归通配符,会自动遍历源文件夹下的所有子目录,不用你手动逐个指定子文件夹。
  • 重名处理:如果多个文件夹里有同名的.c/.h文件,脚本会自动在文件名后加_1、_2这类序号,避免覆盖已有文件。
  • 多源文件夹支持:如果你的.c/.h分散在几个独立的文件夹(不是同一个父目录下的子文件夹),把sourceRootFolder改成单元格数组即可,比如{'D:\SimulinkModel1', 'D:\SimulinkModel2'}。
  • 权限提醒:确保MATLAB有读写源文件夹和目标文件夹的权限,不然可能会报错。如果只是想复制而不是移动,把movefile换成copyfile就行。

内容的提问来源于stack exchange,提问作者Savita J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:27:39