Directory traversal operations under C + +

Source: Internet
Author: User
Tags character set

Recently used C # more, for directory operations DirectoryInfo and directory This kind of feeling easy to use, and suddenly have to write some C + + code, but also to use directory traversal, think about the previous experience, remember as if the CFileFind class in MFC is easy to use, But the concrete use also forgets, also spends some time to look up, or records after this later uses to consult also conveniently.

VC + + under the use of CFileFind class, first of all, in the Project property settings on the "MFC use" set, and then in the header file contains Afx.h, you can finally use the CFileFind class.

Using or looking at the code, Microsoft provides the code to traverse the directory:

void Recurse (LPCTSTR pstr)

{

CFileFind Finder;

Build a string with wildcards

CString Strwildcard (PSTR);

Strwildcard + = _t ("*.*");

Start working for files

BOOL bworking = Finder. FindFile (Strwildcard);

while (bworking)

{

bworking = Finder. FindNextFile ();

Skip. and.. Files Otherwise, we ' d

Recur infinitely!

if (finder. Isdots ())

Continue

If it ' s directory, recursively search it

if (finder. Isdirectory ())

{

CString str = finder. GetFilePath ();

TRACE (_t ("%sn"), (LPCTSTR) str);

Recurse (str);

}

}

Finder. Close ();

}

void Printdirs ()

{

Recurse (_t ("C:"));

}

Code Description:

1. The project chooses the multibyte character set, does not want to tangle _t, lpctsrt and so on;

2. As for Trace, this is a debug macro, almost equivalent to printf, specific reference: http://msdn.microsoft.com/en-us/library/4wyz8787 (v=vs.90). aspx

3. Cfilefind:findnextfile must be called at least in advance getfilename and other member functions before the call, or to the error. So bworking = Finder. FindNextFile (); This line is in front of the stacking

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.