Link to home
Start Free TrialLog in
Avatar of deepakg76
deepakg76

asked on

function to Rename file using wild card character like ren *.dat to *.txt

I want to rename the files like *.dat to *.txt. Pls. suggest the function for the same that works on both windows as well as unix.
rename function only rename single file.

thanks in advance!
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi deepakg76,

there is no such function in ANSI C ... you can perhaps try system ("rename ... ");

Cheers!
Sunny:o)

Linux tools will let you make this change with a single command:

rename .dat .txt *.dat

Windows has no such equivalent, you'll have to write a program or script to do this.

Kent
for i in `ls directory_name`
do
     mv $i.dat $.txt
done

will convert all dat files in a directory to txt files (extensions)
ASKER CERTIFIED SOLUTION
Avatar of Ajar
Ajar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Hi Ajar,

Nice code, written quickly.  :)

It does miss files with two periods.  "2003.11.12_TestScores.dat"  will be missed do to the test finding the first period.


  temp = strchr (file_name, '.');
  temp1 = temp;
  while (temp1)
  {
    temp1 = strchr (temp1);
    if (temp1)
      temp = temp1;
  }


should solve that.
Kent
Avatar of g0rath
g0rath

not sure about windows atm, but I used scandir() under Unix to get the expressions for what I needed.

#include <stdio.h>
#include <dirent.h>
#include <string.h>

int my_sort( const void *_a, const void *_b)
{
    struct dirent **a = (struct dirent **)_a;
    struct dirent **b = (struct dirent **)_b;

    return(strcmp((*a)->d_name,(*b)->d_name));
}

int my_select( const struct dirent *a )
{
    char *cs = NULL;

        //printf("%s\n", a->d_name);
    cs = strrchr(a->d_name, '.');
    if (cs == NULL)
        return 0;

    if (strcasecmp(cs,".dat") == 0)
        return 1;

    return 0;
}


int main( void )
{
     struct dirent **namelist;
     int n = 0;

     n = scandir(".", &namelist, my_select, my_sort);
     if (n < 0)
     {
          fprintf(stderr, "Error: Scandir()\n");
          exit(1);
     }

     while ( n--)
     {
     // you rename code for namelist[n]->d_name
     printf("%s\n", namelist[n]->d_name);
     }

     return 0;
}
this will handle all files like....

1.dat
1.2.3.dat


etc...

the my_sort() is just there for a complete example, you can just use alphasort() if you wish