修改mp3的文件名的C++代码片段
////////////////////////////////////////////////////////////////////////////////// //用法:命令行输入要处理的mp3所在的文件夹的地址,如果不输入默认当前目录 // //功能:修改所给文件夹下的所有的mp3的文件名字,修改是根据mp3文件的属性给出的名字// //作者:Patrol // //日期:2007.7.3 // ////////////////////////////////////////////////////////////////////////////////// #include <cstring> #include <cstdio> #include <string> #include <windows.h> #include <iostream> using namespace std; char tag[3+1];//MP3头文件标识 char author[30+1];//作者 char title[30+1];//曲目名 char year[4+1];//发行年份 char remark[30+1];//评论 char disc_name[30+1];//专辑名称 bool ReadMp3Info(const char*fn) { FILE*fp ; fp=fopen(fn,"r"); if(!fp) return false ; fseek(fp,-128,SEEK_END); //读取最后128位的mp3信息 fread(tag,1,3,fp); //读取tag tag[3]='\0' ; //如果tag值不为“TAG”,则表示不是一个标准可读信息的MP3文件 if(strcmp(tag,"TAG")!=0)return false ; fread(title,1,30,fp); fread(author,1,30,fp); fread(disc_name,1,30,fp); fread(year,1,4,fp); fread(remark,1,30,fp); fclose(fp); return true ; } void RenameMp3(char *s) { strcpy(title,""); ReadMp3Info(s); wchar_t a,b,c=' ';//处理title里存在汉字的情况 for(int i=0;i<30;i+=2) { a=title[i]; a=a<<8; b=title[i+1]; b=b a=a|b;/* char m[3]; m[0]=title[i]; m[1]=title[i+1]; m[2]='\0'; cout<<m<<" title["<<i<<"]="<<hex<<(short)title[i]<<" "<<title[i]<< " title["<<i+1<<"]="<<hex<<(short)title[i+1]<<" "<<title[i+1]<< " a="<<hex<<a<<endl; */ if(a==0x2020)//一个空格为0x20,所以两个空格叠加在一起就是0x2020 { title[i]='\0'; // cout<<endl<<"i="<<i<<endl; break; } } //if() string newname(title); newname.append(".mp3"); return ; } /*must be zero when first run*/ bool SearchFileIncludeString(char*DirectoryName,int&nCount) { WIN32_FIND_DATA FileData ; HANDLE hSearch ; char szNewPath[MAX_PATH]; BOOL fFinished=FALSE ; string temp ; SetCurrentDirectory(DirectoryName); hSearch=FindFirstFile("*.mp3",&FileData); if(hSearch==INVALID_HANDLE_VALUE) { char Output[MAX_PATH]; sprintf(Output,"No files found IN %s.\n",DirectoryName); printf(Output); return false ; } else { if((strcmp(FileData.cFileName,".")!=0&&strcmp(FileData.cFileName,"..")!=0)) { ++nCount ; RenameMp3(FileData.cFileName); } } while(!fFinished) { if(!FindNextFile(hSearch,&FileData)) { if(GetLastError()==ERROR_NO_MORE_FILES) { // printf("No more files, Search completed.\n"); fFinished=true ; } else { // printf("Couldn't find next file.\n"); return false ; } } if((strcmp(FileData.cFileName,".")==0)||(strcmp(FileData.cFileName,"..")==0)) continue ; else { if(!(FileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) { ++nCount ; RenameMp3(FileData.cFileName); } else { strcpy(szNewPath,DirectoryName); strcat(szNewPath,"\\"); strcat(szNewPath,FileData.cFileName); SearchFileIncludeString(szNewPath,nCount); ZeroMemory(szNewPath,MAX_PATH); } } } FindClose(hSearch); return true ; } int main(int argc,char *agrv[]) { if(argc<2) { // printf("Please point out the File Directory !"); agrv[1]=(char*)malloc(MAX_PATH); GetCurrentDirectory(MAX_PATH,agrv[1]); // return 1; } int Fcount=0; SearchFileIncludeString(agrv[1],Fcount); // free(argv[1]); return 0; }