tags:

views:

681

answers:

7

I want to remove a particular substring from all the file names in a directory.

-- like 'XYZ.com' from 'Futurama s1e20 - [XYZ.com].avi' --

So basically i need to provide the method with a desired substring, and it has to loop through all file names and compare.

I cant figure out how to loop through all files in a folder using C.

(sorry if this is a repeat)

+3  A: 

Take a look at dirent.h.

mouviciel
+3  A: 

You may use man 3 fts to loop through all files in a folder using C:

http://keramida.wordpress.com/2009/07/05/fts3-or-avoiding-to-reinvent-the-wheel/

+1  A: 

The key functions are _findfirst, _findnext and _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);
msh
The API is different under Linxu / Unix.
Matthias Wandel
A: 
Neeraj
A: 

fts has a nice interface, but it's 4.4BSD and is not portable. (I recently got bitten in the rear by some software with an inherent dependency on fts.) opendir and readdir are less fun but are POSIX standards and are portable.

Norman Ramsey
+1  A: 

I know this answer will get me down-voted, but your problem is perfect for a shell script, (or .cmd script), a PHP script, or PERL script. Doing it in C is more work than the problem is worth.

Eric M
A: 

fts(3) is 4.4BSD, Linux, Mac OS X, ... Just FYI!