How to list only user provided file names from the directory in C?

大城市里の小女人 提交于 2021-01-29 05:57:22

问题


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);
}

回答1:


From comments:
I would like to know how to implement this in my code because I have never used these functions.

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;
}


来源:https://stackoverflow.com/questions/60885920/how-to-list-only-user-provided-file-names-from-the-directory-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!