VC file Directory Common Operation example summary _c language

Source: Internet
Author: User

Generally speaking, in VC file operation has a lot of, this article here contains some common functions, share for everyone reference. Specifically as follows:

1. Determine if a directory exists

Copy Code code as follows:
#include "Windows.h"

Parameters: strpath: Full path to the directory, note do not end with '/'

Return value: Returns True if it is a directory, otherwise returns a false

BOOL folderexist (CString strpath)
{
Win32_find_data WFD;
BOOL rValue = FALSE;
HANDLE hfind = FindFirstFile (strpath, &WFD);
if ((Hfind!=invalid_handle_value) &&
(wfd.dwfileattributes&file_attribute_directory))
{
RValue = TRUE;
}
FindClose (hfind);
return rValue;
}

2. Determine whether a file or directory exists

Parameter: The full name of the file or directory (with the path), can be a file name, or it can be a directory name

Return value: If present, return True, otherwise return false.

Copy Code code as follows:
BOOL fileexist (CString strFileName)
{
CFileFind Ffind;
Return Ffind.findfile (strFileName);
}

3. Create a Directory

Copy Code code as follows:
BOOL CreateFolder (CString strpath)
{
Security_attributes attrib;
/*

Set common properties for a directory

*/
Return:: CreateDirectory (strpath, &attrib);
}

4. File Size:

Parameters: File name, note that if the directory (folder) is given, the function return value does not recursively calculate all file sizes in the directory. So the function only applies to the statistics of the file size.

Return value: File size. The unit is byte.

Copy Code code as follows:
DWORD GetFileSize (CString filepath)
{
Win32_find_data FileInfo;
HANDLE Hfind;
DWORD fileSize;
CString filename;
filename = filepath;
Hfind = FindFirstFile (Filename,&fileinfo);
if (hfind!= invalid_handle_value)
FileSize = Fileinfo.nfilesizelow;

FindClose (hfind);
return fileSize;
}

5. Calculate the size of the folder

Parameters: The full path to the folder. The function does not use the file

Return value: The size of the folder, in bytes.

Copy Code code as follows:
Int64 getfoldersize (CString Strdirpath)
{

CString strFilePath;

Int64 dwdirsize = 0;
strFilePath + = Strdirpath;
strFilePath + = "//*.*";
CFileFind Finder;
BOOL bfind = Finder. FindFile (strFilePath);
while (bfind)
{
bfind = Finder. FindNextFile ();
if (!finder. Isdots ())
{
CString Strtemppath = Finder. GetFilePath ();
if (!finder. Isdirectory ())
{
dwdirsize = Finder. GetLength ();
}
Else
{
Dwdirsize + + getdirsize (Strtemppath);
}
}
}
Finder. Close ();
return dwdirsize;
}

Because this function involves a recursive call, if it is a very large folder, or if there are many subfolders under the folder,

is likely to cause a stack overflow. I tested the system directory D and E, no overflow occurred. So under normal circumstances

can be used. The disk space represented by the return value of Int64,int64 is quite large and there is no possibility of overflow.

6. List all files in a directory (not recursively listed)

Copy Code code as follows:
#include <Windows.h>
#include <tchar.h>
#include <list>
#include <set>
#include <cassert>
#include <string>
typedef std::basic_string<tchar> _tstring; Wide string
typedef std::list<_tstring> _tslist; String Linked list
/*

Returns a list of file names.

Full path to the FilePath directory, without//

filefilterlist file extension list, can be a variety of types of combinations, such as TXT;. XLS;. Doc

isordered whether to sort file names

*/

_tslist Searchfile (LPCTSTR filepath, lpctstr filefilterlist = _t (". *"), bool isordered = TRUE)

{

ASSERT (filepath!= NULL);

TCHAR Buffer[max_path];

#if _msc_ver > 1310

/* 1310 for Microsoft Visual C + +. NET 2003. 1310 Represents/version and a 1.0 point release. The Visual C + + compiler version is 1400, the number.

*/

_tcscpy_s (buffer, filepath); _tcscpy_s is a micro for strcpy_s and strwcpy_s

#else

_tcscpy (Buffer,filepath); //

#endif

_tslist filenamelist; Initial length is 100

Win32_find_data FindData;

HANDLE searchhandle = Invalid_handle_value;

size_t length= _tcslen (filepath);

if (Buffer[length-1]!= _t ('//')
{

_tcscat_s (buffer,_t ("//*")); Add/* to end of string to find all files
}
if ((Searchhandle =:: FindFirstFile (buffer, &finddata))!= Invalid_handle_value)
{

while (:: FindNextFile (Searchhandle, &finddata)!= 0)
{

if (!) ( Finddata.dwfileattributes & File_attribute_directory))/to File
{
if (!_tcsicmp (Filefilterlist, _t (". *"))//output All files to the list

Filenamelist.push_back (Finddata.cfilename);
Else
{
Get file filter list string, a example, file filter '. txt;. XLS;. Doc
_tstring filterstring = filefilterlist;
_tstring filename (finddata.cfilename);
_tstring::size_type index = filename.find_last_of (_t ('. '));
if (index = = _tstring::npos)//file does not have an extension, skip
Continue
Else
{
_tstring extname = Filename.substr (index+1); To get the file name extension
_tstring::size_type exist;
exist = Filterstring.find (Extname);
if (exist!= _tstring::npos)//To determine whether the file extension is in the Extended Name list
Filenamelist.push_back (Finddata.cfilename);
}
}
}
}
}
:: FindClose (Searchhandle);

if (isordered)//if required to sort, sort the list
{
Filenamelist.sort (); The list is sorted using the merge sort
}
return filenamelist;
}

The test code is as follows:

Copy Code code as follows:
LPCTSTR s = _t ("C://temp");
LPCTSTR S1 = _t (". txt;. xls");
_tslist filename = searchfile (S,S1);

Copy (Filename.begin (),
Filename.end (),
Ostream_iterator<_tstring, _tstring::value_type > (Wcout, _t ("n"))
);

Because the function returns a list, there is a huge copy overhead. The individual is also unsure whether the Rvo (return value) will be executed, so if the list is large, it is really bad. The solution is to pass the list as a reference parameter. This saves the cost of a copy.

Copy Code code as follows:
void Searchfile (_tslist& list, LPCTSTR filepath, lpctstr filefilterlist = _t (". *"), bool isordered = TRUE)

The above code is compiled from Visual Studio 2008 and tested to run.

Interested friends can test and run the example of this article to deepen understanding. I hope this article will help you with the C + + program design.

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.