首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

遍历磁盘,得到后缀名为.txt的文件路径,最后的几个路径如何是目录

2013-03-12 
遍历磁盘,得到后缀名为.txt的文件路径,最后的几个路径怎么是目录?#include windows.h#include iostream

遍历磁盘,得到后缀名为.txt的文件路径,最后的几个路径怎么是目录?

#include <windows.h>
#include <iostream>
#include <fstream> 
#include "stdio.h"
using namespace std;

bool Search(TCHAR *Path,TCHAR *File);
//file stream    
//fstream fStream; 
FILE *fp;

int main()
{
//char txtfile[MAX_PATH];
cout<<L"Please input the .txt file name (include path) to record your search result !"<<endl; 
//cin>>txtfile; 
//scanf(txtfile);
cout<<endl<<endl; 
    
fp=fopen("temp.log","w+"); 
if(!fp) 

cout<<L"Can not open the .txt file"<<endl; 
//return 0; 
}
else
{
cout<<"the file is opened !"<<endl; 
}


Search(L"C:",L".txt");
  
fclose(fp); 


system("pause");
return true;
}

bool TcharMarch(TCHAR *fileName,TCHAR *Extension)//文件后缀名匹配
{
int length_of_ext=wcslen(Extension);
int length_of_name=wcslen(fileName);
int i=0;
while(i<length_of_ext)
{
if (fileName[i+(length_of_name-length_of_ext)]!=Extension[i])
{
return false;
}
else
i++;
}
return true;

}

bool Search(TCHAR *Path,TCHAR *File)
{
HANDLE hFind;
WIN32_FIND_DATA wfd;

ZeroMemory(&wfd,sizeof(WIN32_FIND_DATA));
TCHAR PathTemp[MAX_PATH];
memset(PathTemp,0,sizeof(PathTemp));

swprintf(PathTemp,L"%s\\*.*",Path);
hFind=FindFirstFile(PathTemp,&wfd);

if(INVALID_HANDLE_VALUE==hFind)
{
//MessageBox(NULL,L"INVALID_HANDLE_VALUE",L"FindFirstFile",MB_OK);
return false;
}

do
{
if('.'==wfd.cFileName[0])
{
continue;
}

if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
swprintf(PathTemp,L"%s\\%s",Path,wfd.cFileName);
//MessageBox(NULL,PathTemp,"Directory",MB_OK);
//wprintf(PathTemp);
//printf("\n");
Search(PathTemp,File);
}
else
{
//if(0==strcmp(File,wfd.cFileName))
//{
if (TcharMarch(wfd.cFileName,File))
{

swprintf(PathTemp,L"%s\\%s",Path,wfd.cFileName);
//MessageBox(NULL,L"Found",PathTemp,MB_OK);
//printf(PathTemp);
wprintf(PathTemp);
printf("\n");
fwprintf(fp,L"%s\n",PathTemp);
//fprintf(fp,"hello%s\n",PathTemp);
//fStream.write(root,strlen(root)); 
//fStream.write("\",1); 
//fwrite("hello",sizeof(char),6,fp); 
//fputc('\r',fp); 
//fputc('\n',fp);
//fputc('4', fp);
//}
}
}

}while(FindNextFile(hFind,&wfd));

FindClose(hFind);

return true;

}



[解决办法]
你要搜索的不就是路径和目录吗?
[解决办法]
目录名字也可以是a.txt

system("dir /b /a-d c:\\*.* >d:\\allfiles.txt");
//读文件d:\\allfiles.txt的内容即C:\\下所有文件的名字
system("dir /b /ad  c:\\*.* >d:\\alldirs.txt");
//读文件d:\\alldirs.txt的内容即C:\\下所有子目录的名字


请记住,能用shell命令获取文件、文件夹信息或者操作文件、文件夹最好用shell命令获取或者操作,而不要用各种API获取或者操作,因为当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。

[解决办法]
文件c:\a.txt所在目录(路径)难道不是c:\这种的?
[解决办法]

热点排行