如何仅列出C目录中用户提供的文件名?
问题描述:
我知道如何从目录中打印所有文件,但是如何使用用户先前提供的名称在该目录中找到一个特定文件?
I know how to printf all files from the directory,but how i find one specific file in that directory using name provided earlier by user?
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char a,b;
printf("Path:(eg.c:/): ");
scanf("%s",&a);
d = opendir (&a);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
答
来自注释:
我想知道如何在代码中实现此功能,因为我从未使用过这些功能.
由于使用的是Windows,因此 FindFirstFile 和 FindNextFile 可以是用于在目录中搜索文件规范列表,您可以从那里简单地使用 strstr
通过将搜索结果与用户所需的文件名进行比较来隔离所需的文件.
Since you are using Windows, FindFirstFile and FindNextFile can be used to search a directory for a list of filespecs, from there you can simply use strstr
to isolate the file you need by comparing the search result with your user's desired filename.
以下是可以根据您的目的进行修改的示例:
Here is an example that can be modified for your purposes:
#include <stdio.h>
#include <string.h>
#include <windows.h>
void find(char* path,char* file)
{
static int found =0;
HANDLE fh;
WIN32_FIND_DATA wfd;
int i=0;
int j=0;
fh=FindFirstFile(path,&wfd);
if(fh)
{
if(strcmp(wfd.cFileName,file)==0)
{
path[strlen(path)-3]='\0';
strcat(path,file);
FindClose(fh);
return;
}
else
{
while(FindNextFile(fh,&wfd) && found ==0)
{
if(strcmp(wfd.cFileName,file)==0)
{
path[strlen(path)-3]='\0';
strcat(path,file);
FindClose(fh);
found =1;
return;
}
if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
strcmp(wfd.cFileName,"..")!=0 && strcmp(wfd.cFileName,".")!=0)
{
path[strlen(path)-3]='\0';
strcat(path,wfd.cFileName);
strcat(path,"\\*.*");
find(path,file);
}
}
if(found==0)
{
for(i=strlen(path)-1;i>0;i--)
{
if(j==1 && path[i]=='\\')
{
path[i]='\0';
strcat(path,"\\*.*");
break;
}
if(path[i]=='\\')
j=1;
}
}
}
FindClose(fh);
}
}
int main()
{
TCHAR path[512] = "C:\\*.*";
find(path,"notepad.exe");
printf("%s\n",path);
return 0;
}