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.
Using pathlib module To iterate over files in a directory, use the Path. glob(pattern) function, which glob the given relative pattern in the specified directory and yield the matching files.
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).
Use ifile. open(): ifile. open() is mainly used to check if a file exists in the specific directory or not.
#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 ) ;
}
}
}
Although I would personally prefer a script to do this job like
#!/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With