我已經寫了一個函數來重命名目錄中的文件,以便它們以數字順序命名。不幸的是,這個函數似乎丟掉了一些文件並重新命名了一些文件。可能,我不明白readdir()和rename()後面的邏輯。任何人都可以幫忙,這裏是我的代碼的摘錄;readdir()如何與rename()一起使用?
while(((entry->readdir(dirp))!=NULL)
{
strcpy(t1_string,entry->d_name);
exception1=strcmp(entry->d_name,".");
exception2=strcmp(entry->d_name,"..");
exception3=strcmp(entry->d_name,".svn");
if((exception1!=0)&&(exception2!=0)&&(exception3!=0))
{
token2=strchr(t1_string,'.'); //extension part
num_files++;
if(num_files%4==1)
utt++;
sprintf(utt_n,"%d",utt);
strcpy(newfilename, utt_s); //utt_s is a constant string
strcat(newfilename,utt_n);
strcat(newfilename,token2);
rename(entry->d_name,newfilename);
}
} //End of the while loop
用'printf(「mv -i%s%s \ n」,entry-> d_name,newfilename)替換'rename(entry-> d_name,newfilename);''end看看它試圖做什麼。然後:運行創建的腳本。 – joop
所需的新名稱是所需的順序,但舊名稱以紊亂的方式出現,沒有觀察到順序。讓我尋找另一種方式來做到這一點。 – user4898148
用單個snprintf()替換一堆strcat(),並確保newfilename足夠大。 – joop