新置MP3一件,居然没有随机播放的功能,坑啊!身为程序媛一枚,自己动手吧~
获取当前路径:
char buf[1000]; GetCurrentDirectory(1000,buf); string cur_folder_file = string(buf)+"\\*.mp3";获取当前路径mp3文件列表:
void getMp3Names(string filepath,vector<string> &names) { names.clear(); WIN32_FIND_DATA f; HANDLE h = FindFirstFile(filepath.c_str() , &f); if(h != INVALID_HANDLE_VALUE) { do { names.push_back(f.cFileName); } while(FindNextFile(h, &f)); } FindClose(h); }随机重命名mp3文件(命名为num.mp3,如5.mp3):
void renameMp3Names(vector<string> &names){ int mp3_num = names.size(); vector<bool> used_names(mp3_num,false); srand(time(NULL)); for(int i=0;i<mp3_num;i++){ int new_name_num = -1; while(new_name_num<0){ int tmp= rand()%mp3_num; if(!used_names[tmp]){ new_name_num = tmp; used_names[tmp] = true; } } char char_tmp[100]; itoa(new_name_num,char_tmp,10); string new_name = string(char_tmp)+".mp3"; if(!_access(names[i].c_str(),0)) { if(!rename(names[i].c_str(),new_name.c_str())) { cout<<"RENAME "<<names[i]<<" AS: "<<new_name<<""<<endl; } } } return ; }
基本可以啦~
不过有一点,这个程序运行第二遍就有问题了,因为所有的文件都变成了 num.mp3,再次随机重命名的时候就会出现冲突,重名文件存在导致rename()失败!
再小小修改一下:
void renameMp3Names(vector<string> &names){ cout<<"---------------RENAME MP3 FILES---------------"<<endl; int mp3_num = names.size(); vector<bool> used_names(mp3_num,false); srand(time(NULL)); for(int i=0;i<mp3_num;i++){ int new_name_num = -1; while(new_name_num<0){ int tmp= rand()%mp3_num; if(!used_names[tmp]){ new_name_num = tmp; used_names[tmp] = true; } } char char_tmp[100]; itoa(new_name_num,char_tmp,10); string new_name = string("tmp")+string(char_tmp)+".mp3"; if(!_access(names[i].c_str(),0)) { if(!rename(names[i].c_str(),new_name.c_str())) { cout<<"RENAME "<<names[i]<<" AS: "<<new_name<<""<<endl; names[i] = new_name; //used_names[i] =false; } } } for(int i=0;i<mp3_num;i++) used_names[i] = false; cout<<endl; cout<<"-------------AGAIN RENAME MP3 FILES-------------"<<endl; for(int i=0;i<mp3_num;i++){ int new_name_num = -1; while(new_name_num<0){ int tmp= rand()%mp3_num; if(!used_names[tmp]){ new_name_num = tmp; used_names[tmp] = true; } } char char_tmp[100]; itoa(new_name_num,char_tmp,10); string new_name = string(char_tmp)+".mp3"; if(!_access(names[i].c_str(),0)) { if(!rename(names[i].c_str(),new_name.c_str())) { cout<<"RENAME "<<names[i]<<" AS: "<<new_name<<""<<endl; } } } cout<<endl; return ; }
大功告成啦!