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

Take a look at dirent.h.


#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


You may use FTS(3) to loop through all files in a folder using C:

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

Tags:

C