2011-09-03 42 views
0

如何重命名多個文件是這樣的:重命名序列中的C#或多個文件C++

file.txt , anotherfile.txt , log.txt 

弄成這個樣子:

file1.txt , file2.txt , file3.txt 

我如何在C#或在C這樣做++ ?

+2

你需要在c#或C++中完成嗎?這可以很容易地在一個shell腳本中完成,而且很少費力。如果不需要用c#或C++來完成,你是在運行linux還是windows? – jedwards

+0

C++沒有語言中文件名和目錄的概念,所以您需要一個依賴於平臺的解決方案(或Boost)。 –

+0

如果你在linux上,'man prename'; –

回答

2

使用File.Move Method爲:

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

如果f是FULLPATH,那麼你就可以請改爲:

File.Move(f.FullName, 
     Path.Combine(f.Directory.ToString(), string.Format("file{0}.txt", i)); 
+1

你好,謝謝你的回答,但我認爲我要和Nawaz – shandoosheri

0

在C#中,你可以使用File.Move(source, dest)

當然,你可以通過編程做:

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); 
} 
1

這會在你使用的是基於SH-殼工作:

#!/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 

工作中的腳本:

[[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 
1

在C++中,你最終會使用

std::rename(frompath, topath); 

執行該操作。 TR2提議N1975涵蓋此功能。但是,在此之前,在不久的將來使用boost :: rename,並在最終放置之前批准tr2 :: rename。

循環並使用任何你想要的名字。不知道你是否試圖添加數字,因爲當前的問題說1,2,2。