用Matlab来备份文件夹

来源:互联网 发布:恺英网络市值 编辑:程序博客网 时间:2024/05/18 03:23

用Matlab来备份文件夹

由于各种各的原因,我们需要备份一些文件夹,例如过几天OneDrive的容量将减少,不想升级的用户必须删减内容或者备份内容。但是简单的复制文件夹会造成一些问题,例如导致历史数据丢失、少量的变动也需要复制所有数据。

为了克服这个问题,我用Matlab写了一个简单的文件夹备份程序,实现以下功能:

  1. 如果目标路径没有该文件,则复制该文件
  2. 如果目标路径有该文件,但源路径的文件更新了,则复制该文件到目标路径
  3. 目标路径有而源路径没有的文件则保持不变

具体代码如下:

function backup_folder(folder1,folder2)%% back up a folder%    Copyright 2016 C. Guan%  This program is free software: you can redistribute it and/or%  modify it under the terms of the GNU General Public License version%  3.0 as published by the Free Software Foundation.%  This program is distributed in the hope that it will be useful, but%  WITHOUT ANY WARRANTY; without even the implied warranty of%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU%  General Public License for more details.files1=dir(folder1);files2=dir(folder2);for i=1:size(files1,1)    if strcmp(files1(i).name,'.') || strcmp(files1(i).name,'..')        % the current path is '.' or '..'        fprintf('%s \n',files1(i).name);    else        % the current path is a true path        if isdir([folder1,'/',files1(i).name])            % the current path is a folder            fprintf('%s is a folder\n',files1(i).name);            % check if folder2 has this dir            if exist([folder2,'/',files1(i).name],'dir')                % folder2 has this dir                backup_folder([folder1,'/',files1(i).name],[folder2,'/',files1(i).name]);            else                % folder2 does not has this dir                fprintf('%s does not have folder <%s> . Create and copy.\n',folder2,files1(i).name)                mkdir([folder2,'/',files1(i).name])                try                    copyfile([folder1,'/',files1(i).name,'/*'],[folder2,'/',files1(i).name,'/']);                end            end        else            % the current path is a document            fprintf('%s is a document\n',files1(i).name);            if exist([folder2,'/',files1(i).name])                % the destination folder has this document                temp=dir([folder2,'/',files1(i).name]);                if temp.datenum<files1(i).datenum                    fprintf('%s in %s is newer, copy it to %s \n',files1(i).name,folder1,folder2);                    copyfile([folder1,'/',files1(i).name],[folder2,'/'],'f');                end            else                copyfile([folder1,'/',files1(i).name],[folder2,'/']);            end        end    endend

下面举个例子来说明该函数的用法。
在桌面上创建以下路径和文件:

  • test1
    • 1.txt
    • 1
      • 2.txt
      • 2
        • 3.txt

运行

backup_folder('test1','F:/Test')

会将所有文件复制到目标路径,编辑1.txt添加文字,再运行上面命令会更新目标路径的对应文件。在文件夹2里创建文件,再运行该命令会在目标路径里得到创建的文件。

利用该函数可以轻松一键实现文件备份,例如备份OneDrive。本人利用该函数实现OneDrive增量备份,如下图所示:
运行结果截图

0 0
原创粉丝点击