Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through all files in a folder using C?

Tags:

c

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.

like image 784
NSRover Avatar asked Aug 13 '09 09:08

NSRover


People also ask

Which loop can be used to iterate over files in a directory?

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.

How do I loop a directory in bash?

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).

How do you check if a file is a directory in C++?

Use ifile. open(): ifile. open() is mainly used to check if a file exists in the specific directory or not.


1 Answers

#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

like image 173
sud03r Avatar answered Sep 23 '22 04:09

sud03r