문제

방금 C ++를 배우기 시작했으며 현재 CodeBlocks를 사용하고 있습니다. 나는 서브 다이어를 포함하여 디렉토리에서 파일을 검색 할 수있는 응용 프로그램을 작성하고 싶지만 이것에 대한 좋은 예를 찾을 수없는 것 같습니다. 나는 이것이 부스트와 같은 라이브러리를 통해서만 가능하다는 것을 읽었습니다.

  1. 이것이 사실입니까?
  2. 도서관없이 수행 할 예가 있습니까?

미리 감사드립니다

도움이 되었습니까?

해결책

예를 들어 Linux의 ReadDir, OS 시스템 호출을 사용하여 사용할 수도 있습니다. Boost (및 기타 라이브러리)를 사용하면 여러 (모두) OS에 대한 휴대용 코드를 작성할 수 있습니다.

여기에서 정교한 예제를 찾을 수 있습니다 http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

다른 팁

예, 사실입니다. Standard C ++에는 디렉토리의 내용을 나열하기위한 API가 없습니다.

따라서 라이브러리 (부스트 또는 기타) 또는 사용중인 운영 체제 (Windows의 FindFirstFile/FindNextFile, Opendir/Readdir)를 통해 도서관 (부스트 또는 기타) 또는 기본 호출을 통해 수행합니다. 다른 답변에는 예제 코드가 있습니다.

그러나 방금 C ++를 배우기 시작했다면 지금은 이것들과 어려움을 겪지 않는 것이 낫습니다. 처음에는 표준 C ++ 학습에 중점을 둡니다. 당신이 생각한 응용 프로그램을 작성하는 것은 유용한 연습이지만 표준 C ++에 더 익숙해 질 때까지 조금 연기합니다.

부스트는 디렉토리를 스캔하는 유일한 방법은 아니지만 플랫폼 중립적 인 방식으로 플랫폼 별 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;
}

이 스크립트는 시스템 드라이브에서 파일 생성 및 수정 날짜 정보를 수집하는 데 사용되며 모든 날짜를 검색하여 결과를 알 수 있으며 모든 출력이 플랫 파일에 저장되므로 로그를 쉽게 볼 수 있습니다. 이 프로그램을 실행하기 전에 출력 플랫 파일 (filelist.txt)의 읽기/쓰기 권한을 확인하십시오.

주어진 검색 날짜에 모든 파일이 작성/업데이트되는 내용을 아는 데 도움이됩니다. 대부분의 맬웨어 프로그램은 파일을 주입/영향을 미치므로 영향을받는 파일을 디버깅하는 데 도움이됩니다. Windows 플랫폼에서 Borland C ++ 5.5 버전을 사용 하여이 스크립트를 작성했습니다.

내 기술 블로그에서 소스 코드를 찾으십시오. http://www.algonuts.info/how-trace-file-creation-and-modification-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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top