C++实现给指定目录下的除目录外的所有文件添加指定的后缀名
qianghaohao(孤狼)
用C++动手写了个小工具:给指定目录下的除目录外的所有文件添加指定的后缀名。
运行环境:linux平台
使用方法:./rename_file 目录名 后缀名
使用示例:./rename_file /home/qiang1994/hello .html //给/home/qiang1994/hello目录下
//除目录文件外的所有文件添加.html后缀
源代码如下:
#include<iostream>
#include<stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <cstring>
/**********************************************************************
created: 2016/01/20
created: 20:1:2016 21:04
filename: rename_file.cpp
file base: main
file ext: cpp
author: qianghaohao
pupose: The function of this program is to give all
the files under the directory specified by
the user to add the suffix, except catalog file
usage: command dir_name suff_name
**********************************************************************/
int main(int argc, char **argv)
{
DIR *dir;
struct dirent *ptr;
if (argc < 3)
{
std::cout << "Usage:" << argv[0] << " dir_name suff_name" << std::endl;
return -1;
}
std::cout << "directory:" << argv[1] << std::endl; //print current dir_name
if ((dir = opendir(argv[1])) == NULL) //open directory
{
std::cout << "open directory failed..." << std::endl;
return -2;
}
std::string new_name;
std::string old_name;
while ((ptr = readdir(dir)) != NULL)
{
if (ptr->d_type != DT_DIR) //if file is not directory
{
old_name = argv[1];
old_name += "/";
old_name += ptr->d_name; //old name
new_name = argv[1];
new_name += "/";
new_name += ptr->d_name;
std::cout << new_name << " to ";
new_name += argv[2]; //new name include suffix
std::cout << new_name;
if (rename(old_name.c_str(), new_name.c_str()) == 0) //rename file not directory
{
std::cout << " successed..." << std::endl;
}
else
{
std::cout << " failed..." << std::endl;
}
}
}
closedir(dir); //close directory
std::cout << " complete!" << std::endl;
return 0;
}