如何在 C++ 中执行文件搜索

发布于 2024-08-12 18:22:17 字数 174 浏览 10 评论 0原文

我刚刚开始学习 C++,目前正在使用代码块。 我想编写一个应用程序,可以搜索目录中的文件(包括其子目录),但我似乎找不到任何好的示例,并且我在某处读到这只能通过像 boost 这样的库来实现。

  1. 这是真的吗?
  2. 有没有在没有库的情况下执行此操作的示例?

提前致谢

I just started learning C++ and am currently using codeblocks.
I want to write an application that can search for files in a directory including its subdirs, but I cant seem to find any good examples for this and I've read somewhere that this is only possible through a library like boost.

  1. Is this true?
  2. Are there any examples for doing it without library?

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

南街九尾狐 2024-08-19 18:22:17

也可以通过操作系统系统调用来使用它,例如 Linux 上的 readdir。 boost(和其他库)将允许您为多个(所有?)操作系统编写可移植代码。

在这里您可以找到详细的示例http://faq。 cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

It's also possible to use it using OS system calls, readdir on linux for example. boost (and other libraries) will allow you to write portable code for several (all?) OSes.

Here u can find elaborate examples http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

別甾虛僞 2024-08-19 18:22:17

是的,确实如此:标准 C++(C++17 之前)没有用于列出目录内容的 API。

因此,您可以通过库(Boost 或其他)或通过您正在使用的操作系统的本机调用(Windows 上的 FindFirstFile/FindNextFile,Unix 上的 opendir/readdir)来完成此操作。其他答案有示例代码。

但是,如果您刚刚开始学习 C++,那么现在最好不要纠结于这些问题。开始时重点学习标准 C++。编写您想要的应用程序是一项有用的练习,但我会稍微推迟一下,直到您更熟悉标准 C++ 之后。

Yes, it's true: standard C++ (before C++17) does not have APIs for listing the content of a directory.

So you either do it through a library (Boost or others) or through the native calls for the operating system you're using (FindFirstFile/FindNextFile on Windows, opendir/readdir on Unix). Others answers have example code.

But if you just started learning C++ it is probably better to not struggle with these for now. Focus on learning standard C++ for the beginning. Writing the application you had in mind is an useful exercise but I would postpone it a little until after you are more familiar with standard C++.

嘴硬脾气大 2024-08-19 18:22:17

Boost 不是扫描目录的唯一方法,但它可能是以与平台无关的方式执行此操作的最简单方法 - 即不使用特定于平台的 API(例如 Win32)。

这是一个使用 boost 的简单示例:

#include <boost/filesystem.hpp>
#include <iostream>
#include <iterator>
#include <set>

std::set<boost::filesystem::path> getDirContents (const std::string& dirName)
{
    std::set<boost::filesystem::path> paths;
    std::copy
        ( boost::filesystem::directory_iterator (dirName)
        , boost::filesystem::directory_iterator ()
        , std::inserter (paths, paths.end ())
        );

    return paths;
}

int main (int argc, char* argv[])
{
    std::set<boost::filesystem::path> paths = getDirContents ("C:\\");
    std::copy
        ( paths.begin ()
        , paths.end ()
        , std::ostream_iterator<boost::filesystem::path> (std::cout, "\n")
        );
    return 0;
}

Boost isn't the only way of scanning directories but it's probably the easiest way to do it in a platform-neutral way - i.e. without using a platform-specific API (such as Win32).

Here's a simple example using boost:

#include <boost/filesystem.hpp>
#include <iostream>
#include <iterator>
#include <set>

std::set<boost::filesystem::path> getDirContents (const std::string& dirName)
{
    std::set<boost::filesystem::path> paths;
    std::copy
        ( boost::filesystem::directory_iterator (dirName)
        , boost::filesystem::directory_iterator ()
        , std::inserter (paths, paths.end ())
        );

    return paths;
}

int main (int argc, char* argv[])
{
    std::set<boost::filesystem::path> paths = getDirContents ("C:\\");
    std::copy
        ( paths.begin ()
        , paths.end ()
        , std::ostream_iterator<boost::filesystem::path> (std::cout, "\n")
        );
    return 0;
}
迟月 2024-08-19 18:22:17

该脚本用于从系统驱动器收集文件创建和修改日期信息,我们可以搜索任何日期以了解结果,并且所有输出将存储在平面文件中,因此更容易查看日志。在运行此程序之前,请确认输出平面文件(FileList.txt)的读/写权限。

它有助于了解在给定的搜索日期创建/更新的所有文件。大多数恶意软件程序都会尝试注入/影响文件,因此它有助于调试这些受影响的文件。我在Windows平台下使用Borland C++ 5.5版本编写了这个脚本。

请从我的技术博客中找到源代码 - http://www.algonuts.info/how-to-trace-file-creation-and-modification-date-using-c-programming.html

#include<iostream.h>
#include<conio.h>
#include<dirent.h>
#include<dir.h>
#include<process.h>
#include<string.h>
#include<stdio.h>
#include<io.h>
#include<dos.h>
#include<sys/stat.h>

int found=0;
struct ffblk vfile;
unsigned long int udata;
char ch,present[MAXPATH];
int year,month,day;

int next_directory(char *);
void scan_directory(char *);

void main(int account,char *arg[],char *env[])
{   
    clrscr();
    getcwd(present,MAXPATH);

    DIR *dir; 
    struct dirent *temp;
    cout<<"\nWelcome to Finder for file view";
    cout<<"\n\nEnter drive:";
    cin>>ch;

    char base[]="X:\\";
    base[0]=ch;
    if ((dir = opendir(base)) == NULL)
    { 
        clrscr();
        cout<<"\nError : Derive not found";  
        getch(); 
        exit(0); 
    }
    else
    {
        if(access("FileList.txt",0)==0)
        unlink("FileList.txt");
        cout<<"\n\n\nScan Date Details:";
        cout<<"\n\nEnter Year:";
        cin>>year;
        cout<<"\nEnter Month:";
        cin>>month;
        if( !(month>=1 && month<=12) )
        {
            clrscr();
            cout<<"\nError:Value of month is not exist";
            getch();
            exit(0);                
        }
        cout<<"\nEnter Day:";
        cin>>day;
        if( !(day>=1 && day<=31) )
        {
            clrscr();
            cout<<"\nError:Value of day is not exist";
            getch();
            exit(0);                
        }
    }

    scan_directory(base);
    while ((temp = readdir(dir)) != NULL)
    {
        char  *directory = (char *) malloc(3+strlen(temp->d_name)+1);
        strcpy(directory,base);
        strcat(directory,temp->d_name);
        next_directory(directory);
        free(directory);
    }
    closedir(dir);

    clrscr();
    if(access("FileList.txt",0)==0)
    cout<<"\n\nSystem: Successfully Find all files and stored in FileList.txt";
    else
    cout<<"\n\nSystem: No file has Modified on"<<day<<"//"<<month<<"//"<<year;
    sleep(3);   
}

int next_directory(char *path)
{
    int count=0;
    DIR *dirtemp; 
    char *hold,*temp;
    struct dirent *ptemp;


    hold=path;
    if ((dirtemp = opendir(path)) != NULL)
    scan_directory(path);
    else
    return 0;


    while ((ptemp = readdir(dirtemp)) != NULL)
    {     
        char *directory = (char *) malloc(1+strlen(ptemp->d_name)+1);
        directory[0]='\\';
        strcpy(directory+1,ptemp->d_name);
        if(directory[1]!='\.')
        {
            count=strlen(hold);
            temp = (char *) malloc(strlen(hold)+strlen(directory)+1);
            strcpy(temp,hold);
            strcat(temp,directory);
            free(directory);
            if(opendir(temp)!=NULL)
            next_directory(temp); 
            temp[count]='\0'; 
            free(temp+count+1);
            hold=temp;
        }
        else
        free(directory);
    }
    closedir(dirtemp);
    return 0;
}

void scan_directory(char *tempo)
{
    cout<<"\n"<<tempo;

    FILE *stream;
    struct ftime ft;

    if(present[0]==tempo[0])
    chdir(tempo);  
    else
    {
        setdisk(tempo[0]-65);
        chdir(tempo); 
    }

    udata = findfirst("*.*",&vfile,0x02);
    while (!udata)
    {  
        stream = fopen(vfile.ff_name,"r");
        if(stream==NULL)
        {
            fclose(stream);
            udata=findnext(&vfile);
            continue;
        }
        else
        {
            getftime(fileno(stream), &ft);
            if(year==ft.ft_year+1980 && month==ft.ft_month && day==ft.ft_day)
            {
                //cout<<"\n"<<tempo<<" "<<vfile.ff_name<<"  Hour:"<<ft.ft_hour<<"  Min:"<<ft.ft_min<<"  Sec:"<<ft.ft_tsec *2;
                if(present[0]==tempo[0])    
                system("cd\\");
                chdir(present); 

                char string[25];
                FILE *fp = fopen("FileList.txt","a+");

                if(found==0)
                {
                    fputs("Scan Date: ",fp);
                    itoa(ft.ft_day, string, 10);
                    fputs(string,fp);
                    fputc('\\',fp);

                    itoa(ft.ft_month, string, 10);
                    fputs(string,fp);
                    fputc('\\',fp);

                    itoa((ft.ft_year+1980), string, 10);
                    fputs(string,fp);
                    fputs("\n\n",fp);
                    found=1;
                }

                unsigned get;
                _dos_getfileattr(vfile.ff_name,&get);
                if (get & _A_HIDDEN)
                fputs("[Hidden File]  ",fp);

                get=0;
                if(ft.ft_hour<10)
                get=1;
                itoa(ft.ft_hour, string, 10);
                fputs(string,fp);
                fputc('\\',fp);

                if(ft.ft_min<10)
                get=get+1;
                itoa(ft.ft_min, string, 10);
                fputs(string,fp);
                fputc('\\',fp);

                if(ft.ft_tsec<10)
                get=get+1;
                itoa(ft.ft_tsec, string, 10);
                fputs(string,fp);

                for(int count=0;count<get;count++)
                fputs(" ",fp);

                fputs("  ",fp);
                fputs(tempo,fp);
                fputs("   ",fp);

                fputs(vfile.ff_name,fp);
                fputc('\n',fp);
                fclose(fp);

                if(present[0]==tempo[0])
                chdir(tempo);  
                else
                {
                    setdisk(tempo[0]-65);
                    chdir(tempo); 
                }
            }
            fclose(stream);
        }
        udata=findnext(&vfile);
    }
    if(present[0]==tempo[0])    
    system("cd\\");
    chdir(present);
}

This script is used to collect files creation and modification date information from your system drive, we can search any date to know the results and all output will be stored in a flat file, so its easier to view the log. Before running this program, please confirm the read/write permission for the output flat file (FileList.txt).

It helps to know what all files are created/update on those given search date. Most malware programs try to inject/affect the files, so it helps to debug those affected files. I wrote this script using Borland C++ 5.5 Version under Windows Platform.

Please find the source code from my tech blog - http://www.algonuts.info/how-to-trace-file-creation-and-modification-date-using-c-programming.html

#include<iostream.h>
#include<conio.h>
#include<dirent.h>
#include<dir.h>
#include<process.h>
#include<string.h>
#include<stdio.h>
#include<io.h>
#include<dos.h>
#include<sys/stat.h>

int found=0;
struct ffblk vfile;
unsigned long int udata;
char ch,present[MAXPATH];
int year,month,day;

int next_directory(char *);
void scan_directory(char *);

void main(int account,char *arg[],char *env[])
{   
    clrscr();
    getcwd(present,MAXPATH);

    DIR *dir; 
    struct dirent *temp;
    cout<<"\nWelcome to Finder for file view";
    cout<<"\n\nEnter drive:";
    cin>>ch;

    char base[]="X:\\";
    base[0]=ch;
    if ((dir = opendir(base)) == NULL)
    { 
        clrscr();
        cout<<"\nError : Derive not found";  
        getch(); 
        exit(0); 
    }
    else
    {
        if(access("FileList.txt",0)==0)
        unlink("FileList.txt");
        cout<<"\n\n\nScan Date Details:";
        cout<<"\n\nEnter Year:";
        cin>>year;
        cout<<"\nEnter Month:";
        cin>>month;
        if( !(month>=1 && month<=12) )
        {
            clrscr();
            cout<<"\nError:Value of month is not exist";
            getch();
            exit(0);                
        }
        cout<<"\nEnter Day:";
        cin>>day;
        if( !(day>=1 && day<=31) )
        {
            clrscr();
            cout<<"\nError:Value of day is not exist";
            getch();
            exit(0);                
        }
    }

    scan_directory(base);
    while ((temp = readdir(dir)) != NULL)
    {
        char  *directory = (char *) malloc(3+strlen(temp->d_name)+1);
        strcpy(directory,base);
        strcat(directory,temp->d_name);
        next_directory(directory);
        free(directory);
    }
    closedir(dir);

    clrscr();
    if(access("FileList.txt",0)==0)
    cout<<"\n\nSystem: Successfully Find all files and stored in FileList.txt";
    else
    cout<<"\n\nSystem: No file has Modified on"<<day<<"//"<<month<<"//"<<year;
    sleep(3);   
}

int next_directory(char *path)
{
    int count=0;
    DIR *dirtemp; 
    char *hold,*temp;
    struct dirent *ptemp;


    hold=path;
    if ((dirtemp = opendir(path)) != NULL)
    scan_directory(path);
    else
    return 0;


    while ((ptemp = readdir(dirtemp)) != NULL)
    {     
        char *directory = (char *) malloc(1+strlen(ptemp->d_name)+1);
        directory[0]='\\';
        strcpy(directory+1,ptemp->d_name);
        if(directory[1]!='\.')
        {
            count=strlen(hold);
            temp = (char *) malloc(strlen(hold)+strlen(directory)+1);
            strcpy(temp,hold);
            strcat(temp,directory);
            free(directory);
            if(opendir(temp)!=NULL)
            next_directory(temp); 
            temp[count]='\0'; 
            free(temp+count+1);
            hold=temp;
        }
        else
        free(directory);
    }
    closedir(dirtemp);
    return 0;
}

void scan_directory(char *tempo)
{
    cout<<"\n"<<tempo;

    FILE *stream;
    struct ftime ft;

    if(present[0]==tempo[0])
    chdir(tempo);  
    else
    {
        setdisk(tempo[0]-65);
        chdir(tempo); 
    }

    udata = findfirst("*.*",&vfile,0x02);
    while (!udata)
    {  
        stream = fopen(vfile.ff_name,"r");
        if(stream==NULL)
        {
            fclose(stream);
            udata=findnext(&vfile);
            continue;
        }
        else
        {
            getftime(fileno(stream), &ft);
            if(year==ft.ft_year+1980 && month==ft.ft_month && day==ft.ft_day)
            {
                //cout<<"\n"<<tempo<<" "<<vfile.ff_name<<"  Hour:"<<ft.ft_hour<<"  Min:"<<ft.ft_min<<"  Sec:"<<ft.ft_tsec *2;
                if(present[0]==tempo[0])    
                system("cd\\");
                chdir(present); 

                char string[25];
                FILE *fp = fopen("FileList.txt","a+");

                if(found==0)
                {
                    fputs("Scan Date: ",fp);
                    itoa(ft.ft_day, string, 10);
                    fputs(string,fp);
                    fputc('\\',fp);

                    itoa(ft.ft_month, string, 10);
                    fputs(string,fp);
                    fputc('\\',fp);

                    itoa((ft.ft_year+1980), string, 10);
                    fputs(string,fp);
                    fputs("\n\n",fp);
                    found=1;
                }

                unsigned get;
                _dos_getfileattr(vfile.ff_name,&get);
                if (get & _A_HIDDEN)
                fputs("[Hidden File]  ",fp);

                get=0;
                if(ft.ft_hour<10)
                get=1;
                itoa(ft.ft_hour, string, 10);
                fputs(string,fp);
                fputc('\\',fp);

                if(ft.ft_min<10)
                get=get+1;
                itoa(ft.ft_min, string, 10);
                fputs(string,fp);
                fputc('\\',fp);

                if(ft.ft_tsec<10)
                get=get+1;
                itoa(ft.ft_tsec, string, 10);
                fputs(string,fp);

                for(int count=0;count<get;count++)
                fputs(" ",fp);

                fputs("  ",fp);
                fputs(tempo,fp);
                fputs("   ",fp);

                fputs(vfile.ff_name,fp);
                fputc('\n',fp);
                fclose(fp);

                if(present[0]==tempo[0])
                chdir(tempo);  
                else
                {
                    setdisk(tempo[0]-65);
                    chdir(tempo); 
                }
            }
            fclose(stream);
        }
        udata=findnext(&vfile);
    }
    if(present[0]==tempo[0])    
    system("cd\\");
    chdir(present);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文