主要通过rename()函数来实现,不过如果新路径文件已存在则会直接覆盖,如果像要询问后操作是否覆盖,可以通过调用
access()函数来处理;
小记:以下仅供参考,经测试,直接使用rename()函数就可以实现mv的功能。之所以贴出该代码,其中宏定义的打印函数值得借鉴
源码
#include <stdio.h>
#include <dirent.h>
#include <string.h>
typedef unsigned char BYTE;
typedef unsigned int DWORD;
typedef unsigned short WORD;
#define pri(fmt, ...) printf("["__FILE__"] <%s>_<%d> " ,__FUNCTION__,__LINE__ );\
printf(fmt, ##__VA_ARGS__);
int main()
{
/* 给文件重命名时保存临时变量 */
BYTE newname[80] = {0};
memset(newname, 0 ,sizeof(newname));
/* 文件描述符 */
struct dirent *dirp;
DIR *dp;
/* 局部变量保存文件名称 */
BYTE buf[128][64];
/* 局部变量保存文件名个数 */
BYTE num=0;
char *path = "/mnt/hgfs/Ubuntu12.04-share/test/2_file/test_dir";
/* 打开路径 */
if ((dp = opendir(path))== NULL)
{
pri("opendir error \n");//打开目录失败
return -1;
}
/* 更换到当前目录 */
chdir(path);
/* 读取路径下的文件 */
while(dirp = readdir(dp))
{
/* 排除 . 和 .. 目录 */
if((strlen(dirp->d_name)) <= 2)
continue ;
/* 不能在打开目录的情况下,进行重命名。文件busy */
memcpy(buf[num], dirp->d_name, sizeof(dirp->d_name));
num++;
pri(" dirp->d_name : %s \n", dirp->d_name);
}
int i=0;
while(i != num)
{
/* 排除 . 和 .. 目录 */
if((strlen(buf[i])) <= 2)
continue;
memcpy(newname, "new", sizeof("new"));
memcpy(newname+3, buf[i]+3, sizeof(buf[i])-3);
/* 重命名 */
if(rename(buf[i], newname) == 0)
{
pri("Renamed %s to %s !\n", buf[i], newname);
}
else
perror("rename");
pri(" newname : %s \n", newname);
i++;
}
return 0;
}
执行结果
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file#
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file# gcc -o test test.c
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file#
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file#
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file# ls ./test_dir/
old_1.h264 old_2.h264 old_3.h264 old_4.h264 old_5.h264
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file# ./test
[test.c] <main>_<48> dirp->d_name : old_1.h264
[test.c] <main>_<48> dirp->d_name : old_2.h264
[test.c] <main>_<48> dirp->d_name : old_3.h264
[test.c] <main>_<48> dirp->d_name : old_4.h264
[test.c] <main>_<48> dirp->d_name : old_5.h264
[test.c] <main>_<64> Renamed old_1.h264 to new_1.h264 !
[test.c] <main>_<69> newname : new_1.h264
[test.c] <main>_<64> Renamed old_2.h264 to new_2.h264 !
[test.c] <main>_<69> newname : new_2.h264
[test.c] <main>_<64> Renamed old_3.h264 to new_3.h264 !
[test.c] <main>_<69> newname : new_3.h264
[test.c] <main>_<64> Renamed old_4.h264 to new_4.h264 !
[test.c] <main>_<69> newname : new_4.h264
[test.c] <main>_<64> Renamed old_5.h264 to new_5.h264 !
[test.c] <main>_<69> newname : new_5.h264
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file# ls ./test_dir/
new_1.h264 new_2.h264 new_3.h264 new_4.h264 new_5.h264
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file#