【Linux-ln拓展】可用于同时创建多个硬链接同时备份多个文件的程序

来源:互联网 发布:java web文件管理系统 编辑:程序博客网 时间:2024/06/05 14:11

最经学习了硬链接命令ln,但发现无法同时创建多个硬链接。同时也为了以后备份资料,以防止误删产生的严重后果。做了一个小程序lnd;

format:lnd sorceDirectoryPath destinationDirecotyPath

功能:为sorceDirectoryPath 中的各个文件创建一个硬链接到destinationDirecotyPath中,若destinationDirecotyPath不存在,那么将递归创建目录

缺点:若sorceDirectoryPath 中也含有其他目录,则不进行递归操作

若想在系统任意地方使用该命令,那么将lnd的可执行程序放入 /bin 中, lnd在当前目录下:sudo mv lnd /bin

附上源码:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/*
format: lnd srcDir desDir
func: make a backups to the file of "srcDir" directory in the objDir.
if objDir is not exited, the func will create it.
*/
int main(const int argc,const char* argv[])
{
if (argc < 3)
{
printf("Format err..\n\tps:lnd srcDir objDir\n");
return -1;
}
DIR* srcDir = opendir(argv[1]);//open srcDir
if (srcDir == NULL)
{
printf("%s\n", strerror(errno));
return -2;
}


DIR* desDir = opendir(argv[2]);//open desDir
if (desDir == NULL)//ensure the desDir exist
{
char* desDir[128];
memset(desDir, 0, sizeof(desDir));
strcat((char*)desDir, "mkdir ");
strcat((char*)desDir, argv[2]);
strcat((char*)desDir, " -p");
system((char*)desDir);
}
else
{
closedir(desDir);
}
// link hard create
struct dirent* dient = readdir(srcDir);
char srcPath[128], desPath[128];
char cmd[256];
while (dient != NULL)
{
if (strcmp(dient->d_name,"..") != 0 && strcmp(dient->d_name, ".") != 0)
{
memset(srcPath, 0, sizeof(srcPath));
memset(desPath, 0, sizeof(desPath));
memset(cmd, 0, sizeof(cmd));
//-----------
strcat(srcPath, argv[1]);
if (argv[1][strlen(argv[1])] != '/')
strcat(srcPath, "/");
strcat(srcPath, dient->d_name);
//-----------
strcat(desPath, argv[2]);
if (argv[2][strlen(argv[2])] != '/')
strcat(desPath, "/");
strcat((char*)desPath, dient->d_name);
//strcat((char*)desPath, ".hard");
//-----------
strcat((char*)cmd, "ln ");
strcat((char*)cmd, srcPath);
strcat((char*)cmd, " ");
strcat((char*)cmd, desPath);
//-----------
system((char*)cmd);
//-----------
}
dient = readdir(srcDir);
}
closedir(srcDir);
return 0;
}

原创粉丝点击