当前位置: 动力学知识库 > 问答 > 编程问答 >

rename multiple file in a sequence c# or c++

问题描述:

How can I rename multiple files like this:

file.txt , anotherfile.txt , log.txt

into something like this :

file1.txt , file2.txt , file3.txt

How can I do this in c# or in c++ ?

网友答案:

Use File.Move Method as:

IEnumerable<FileInfo> files = GetFilesToBeRenamed();
int i = 1;
foreach(FileInfo f in files)
{
    File.Move(f.FullName, string.Format("file{0}.txt", i));
    i++;
}

And if f is a fullpath, then you can do this instead:

File.Move(f.FullName, 
         Path.Combine(f.Directory.ToString(), string.Format("file{0}.txt", i));
网友答案:

This would work in you're using an sh-based shell:

#!/bin/sh
FEXT="txt"      # This is the file extension you're searching for
FPRE="file"     # This is the base of the new files names file1.txt, file2.txt, etc.
FNUM=1;         # This is the initial starting number

find . -name "*.${FEXT}" | while read OFN ; do
    # Determine new file name
    NFN="${FPRE}${FNUM}.${FEXT}"
    # Increment FNUM
    FNUM=$(($FNUM + 1))
    # Rename File
    mv "${OFN}" "${NFN}"
done

The script in action:

[[email protected] renfiles]$ touch abc.txt
[[email protected] renfiles]$ touch test.txt
[[email protected] renfiles]$ touch "filename with spaces.txt"
[[email protected] renfiles]$ ll
total 4
-rw-rw-r-- 1 james james   0 Sep  3 17:45 abc.txt
-rw-rw-r-- 1 james james   0 Sep  3 17:45 filename with spaces.txt
-rwxrwxr-x 1 james james 422 Sep  3 17:41 renfiles.sh
-rw-rw-r-- 1 james james   0 Sep  3 17:45 test.txt
[[email protected] renfiles]$ ./renfiles.sh 
[[email protected] renfiles]$ ll
total 4
-rw-rw-r-- 1 james james   0 Sep  3 17:45 file1.txt
-rw-rw-r-- 1 james james   0 Sep  3 17:45 file2.txt
-rw-rw-r-- 1 james james   0 Sep  3 17:45 file3.txt
-rwxrwxr-x 1 james james 422 Sep  3 17:41 renfiles.sh
网友答案:

In c++, you will eventually use

std::rename(frompath, topath);

to perform the action. TR2 proposal N1975 covers this function. However, until then, use boost::rename for the immediate future, and tr2::rename for the period after approval before final placement.

Loop through and use whatever names you want. Don't quite know if you're trying to add numbers, because the current question says 1, 2, 2.

网友答案:

In c# you can use File.Move(source, dest)

Of course you can do it programatically:

string[] files = new string[] {"file.txt" , "anotherfile.txt" , "log.txt"}:
int index = 0;
string Dest;
foreach (string Source in files)
{
   if (!Files.Exists(Source )) continue;
   do {
       index++;
       Dest= "file"+i+".txt";
   } while (File.Exists(NewName);

   File.Move(Source , Dest); 
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: