2009-08-13 105 views
6

我想从一个目录中的所有文件名称中删除特定字符串:如何循环使用C文件夹中的所有文件?

- 像 'XYZ.com' 从 '飞出个未来s1e20 - [XYZ.com] .AVI' -

所以基本上我需要提供所需的子字符串的方法,它必须遍历所有文件名并进行比较。

我不能使用C.

+2

+1对于公然你知道什么和好的电视节目选择xD。 – zeboidlund 2014-02-18 11:20:39

回答

1

的关键功能是_findfirst,_findnext和_findclose

struct _finddata_t file_info; 
char discard[] = "XYZ.com"; 
char dir[256] = "c:\\folder\\"; 
char old_path[256]; 
char new_path[256]; 
intptr_t handle = 0; 

memset(&file_info,0,sizeof(file_info)); 

strcpy(old_path,dir); 
strcat(old_path,"*.avi"); 

handle = _findfirst(old_path,&file_info); 
if (handle != -1) 
{ 
    do 
    { 
     char *new_name = NULL; 
     char *found = NULL; 
     new_name = strdup(file_info.name); 
     while ((found = strstr(new_name,discard)) != 0) 
     { 
      int pos = found - new_name; 
      char* temp = (char*)malloc(strlen(new_name)); 
      char* remain = found+strlen(discard); 
      temp[pos] = '\0'; 
      memcpy(temp,new_name,pos); 
      strcat(temp+pos,remain); 
      memcpy(new_name,temp,strlen(new_name)); 
      free(temp); 
     } 
     strcpy(old_path,dir); 
     strcat(old_path,file_info.name); 
     strcpy(new_path,dir); 
     strcat(new_path,new_name); 
     rename(old_path,new_path); 
     free(new_name); 
    }while(_findnext(handle,&file_info) != -1); 
} 
    _findclose(handle); 
+1

Linxu/Unix下的API不同。 – 2009-08-13 11:30:52

8
#include <stdio.h> 
#include <dirent.h> 
#include <sys/stat.h> 
#include <sys/types.h> 

int main(int argc, char** argv) 
{ 
struct dirent *dp; 
DIR *dfd; 

char *dir ; 
dir = argv[1] ; 

if (argc == 1) 
{ 
    printf("Usage: %s dirname\n",argv[0]); 
    return 0; 
} 

if ((dfd = opendir(dir)) == NULL) 
{ 
    fprintf(stderr, "Can't open %s\n", dir); 
    return 0; 
} 

char filename_qfd[100] ; 
char new_name_qfd[100] ; 

while ((dp = readdir(dfd)) != NULL) 
{ 
    struct stat stbuf ; 
    sprintf(filename_qfd , "%s/%s",dir,dp->d_name) ; 
    if(stat(filename_qfd,&stbuf) == -1) 
    { 
    printf("Unable to stat file: %s\n",filename_qfd) ; 
    continue ; 
    } 

    if ((stbuf.st_mode & S_IFMT) == S_IFDIR) 
    { 
    continue; 
    // Skip directories 
    } 
    else 
    { 
    char* new_name = get_new_name(dp->d_name) ;// returns the new string 
                // after removing reqd part 
    sprintf(new_name_qfd,"%s/%s",dir,new_name) ; 
    rename(filename_qfd , new_name_qfd) ; 
    } 
} 
} 

虽然我个人比较喜欢脚本来做这个工作,比如


#!/bin/bash -f 
dir=$1 
for file in `ls $dir` 
do 
if [ -f $dir/$file ];then 
    new_name=`echo "$file" | sed s:to_change::g` 
    mv $dir/$file $dir/$new_name 
fi 
done 

0

fts有一个漂亮的界面,但它的4.4BSD而且是不可移植。 (我最近被一些内在依赖fts的软件在后面咬了一口。)opendirreaddir不太好玩,但是POSIX标准并且是便携式的。

4

我知道这个答案会让我下投票,但你的问题是一个完美的shell脚本(或.cmd脚本),PHP脚本或Perl脚本。在C中做这件事比做这件事更值得。

0

FTS(3)是4.4BSD,在Linux,Mac OS X,...仅供参考!

相关问题