c语言遍历所有目录的问题?
程序代码:
我是菜鸟啊,写了个遍历目录的代码。 代码在有些目录中运行时会出错,有些目录一切正常,我把中间一段代码注释了运行全部正常,不知道是哪里出问题了,帮忙分析下。 #include<stdio.h> #include<string.h> #include<windows.h> #include<stdlib.h> #include<stdbool.h> #include<locale.h> bool flag = false; char sentence[] = {0}; void XieWjj(char[], char[]); int FindFiles(char[]); int main(int argc,char const *argv[]) { char path[190]= {0}; GetCurrentDirectory(150, path); //GetModuleFileName(NULL,path,190); //printf("%s\n", path); FindFiles(&path[0]); system("pause"); return 0; } int FindFiles(char *strTemp) { WIN32_FIND_DATA p1; HANDLE h1; int k, j = 0; flag = false; char path2[150] = {0}, path3[150] = {0}, filename[150] = {0}, *name, *ch, name2[150] = {0}; //path2 完整的目录路径 strcpy(path2, strTemp); strcpy(path3, strTemp); strcat(path3, "\\*.*"); h1 = FindFirstFile(path3, &p1); if(h1 == INVALID_HANDLE_VALUE) { printf("%s\n","File no!"); return 0; } do { if (p1.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { //如果是目录 排除 .. 的无效目录 if (p1.cFileName[0] != '.') { sprintf(path3,"%s%s%s",path2,"\\",p1.cFileName); FindFiles(&path3[0]);//递归 } } else { if (strcmp(p1.cFileName, "") != 0) { sprintf(path3,"%s%s%s",path2,"\\",p1.cFileName); name = strrchr(p1.cFileName, '.');//查找最后一个出现的字符位置 ch = name; //char *name = strchr(p,'.'); //查找最前一个出现的字符位置 /* if (strcmp(name, ".m3u8") == 0) { if (flag == false) { flag = true; ch = strchr(p1.cFileName, '.'); //取目录名 k = strlen(p1.cFileName) - strlen(ch); strncpy(name2, p1.cFileName, k); printf("%s\n",name2); sprintf(sentence,"%s%s%s","<?xml version=\"1.0\" encoding=\"UTF-8\"?><tvshow><title>",name2,"</title></tvshow>"); sprintf(filename,"%s%s%s",path2,"\\","tvshow.nfo"); //XieWjj(&filename[0], &sentence[0]); memset(filename , 0, sizeof(filename));//清空数组 memset(sentence , 0, sizeof(sentence));//清空数组 } k = strlen(p1.cFileName) - strlen(name); strncpy(name2, p1.cFileName, k); sprintf(filename,"%s%s%s%s",path2,"\\",name2,".nfo"); j++; printf("."); //printf("%s\n%s\n", p1.cFileName, na); printf("%s\n%s\n", path3,filename); strcpy(sentence, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><episodedetails>"); //XieWjj(&filename[0], &sentence[0]); memset(filename , 0, sizeof(filename));//清空数组 memset(name2, 0, sizeof(name2)); //清空数组 }*/ printf("%s\n",path2); memset(path3, 0, sizeof(path3));//清空数组 } } }while (FindNextFile(h1, &p1)) ; } void XieWjj(char *FileLoad, char *FileName) { /* struct dirent *entry; FILE *fptr; fptr = fopen(FileLoad, "w+b"); if(fptr == NULL) { printf("Error!"); } else { //fgets(FileName, (sizeof FileName/sizeof FileName[0]), (FILE*)fptr); fprintf(fptr,"%s", FileName); } fclose(fptr); */ DWORD dwWriteSize = 0; HANDLE hFile = CreateFile(FileLoad, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("CreateFile fail!\n"); } //SetFilePointer(hFile,0,NULL,FILE_END); if(WriteFile(hFile,FileName,strlen(FileName),&dwWriteSize,NULL)) { //printf("WriteFile OK \n"); } CloseHandle(hFile); }