您的位置:首页 > 运维架构 > Linux

linux 下转换指定目录下所有文件字符编码

2015-04-22 13:46 281 查看
#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <dirent.h>

#include <sys/stat.h>

#include <sys/types.h>

void listDir(char *path, char *cur_dir)

{

DIR *pDir ; //定义一个DIR类的指针

struct dirent *ent ; //定义一个结构体 dirent的指针,dirent结构体见上

int i=0 ;

char childpath[512]; //定义一个字符数组,用来存放读取的路径

char command[512];

char file_name[512];

struct stat statbuf;

pDir=opendir(path); // opendir方法打开path目录,并将地址付给pDir指针

memset(childpath,0,sizeof(childpath)); //将字符数组childpath的数组元素全部置零

memset(file_name,0,sizeof(file_name));

memset(command,0,sizeof(command));

while((ent=readdir(pDir))!=NULL) //读取pDir打开的目录,并赋值给ent, 同时判断是否目录为空,不为空则执行循环体

{

sprintf(file_name, "%s/%s", path, ent->d_name);

if(ent->d_type == DT_DIR) //读取 打开目录的文件类型 并与 DT_DIR进行位与运算操作,即如果读取的d_type类型为DT_DIR (=4 表示读取的为目录)

{

if(strcmp(ent->d_name,".")==0 || strcmp(ent->d_name,"..")==0||strcmp(ent->d_name,"images")==0)

//如果读取的d_name为 . 或者.. 表示读取的是当前目录符和上一目录符, 用contiue跳过,不进行下面的输出

continue;

sprintf(childpath,"%s/%s",path,ent->d_name); //如果非. ..则将 路径 和 文件名d_name 付给childpath, 并在下一行prinf输出

printf("childpath:%s\n",childpath);

listDir(childpath, cur_dir); //递归读取下层的字目录内容, 因为是递归,所以从外往里逐次输出所有目录(路径+目录名),

//然后才在else中由内往外逐次输出所有文件名

}

else //如果读取的d_type类型不是 DT_DIR, 即读取的不是目录,而是文件,则直接输出 d_name, 即输出文件名

{

printf("file name : %s\n",file_name);

sprintf(command, "touch %s.tmp", file_name);

printf("%s\n",command);

system(command);

#if 1

memset(command,0,sizeof(command));

//printf("iconv input:%s/%s\n",cur_dir, file_name );

sprintf(command, "iconv -f gbk -t utf8 %s/%s -o %s/%s.tmp",cur_dir, file_name, cur_dir, file_name);// cur_dir, file_name);

//printf("command ===%s\n", command);

system(command);

memset(command,0,sizeof(command));

sprintf(command, "mv %s/%s.tmp %s/%s", cur_dir, file_name, cur_dir, file_name);

system(command);

//execute iconv command :iconv -f gbk -t utf8 ./test.java

#endif

}

}

}

int main(int argc,char *argv[])

{

char cur[512];

memset(cur,0,sizeof(cur));

getcwd(cur, 512);

listDir(argv[1], cur); //第一个参数为 想要转换的 linux 目录 例如,当前目录为 ./

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐