VC ++ determine the file or folder exists (rpm)

VC ++ to determine whether there is a file or folder

in Windows application projects almost always need to use some file system-related functions, such as: to determine whether a file exists, determine whether the folder is empty, delete the folder and all its children, the calculation of the size of the file folder, and so on. I do not know why, Windows does not provide direct API to perform these operations, so the rivers and lakes began to create the code from a variety of genres, a swords. . .
Avenue stream: GetFileAttributes

Road to Jane Avenue in front of you! For general applications, GetFileAttributes arguably the best API to determine the file or folder exists. Because it features a clear, easy to use, support XP system, and more importantly, it can be the difference between files and folders directly. When we write a file or folder to determine whether the function exists, it should be preferred, or I'll ask you a question: (. Hey, if there is anything wrong = =) tall Avenue you do not go, you si bu si sa? Code as follows:

// determines whether a file exists
BOOL IsFileExist (const CString & csFile)
{
    DWORD = dwAttrib the GetFileAttributes (csFile);
    return INVALID_FILE_ATTRIBUTES = dwAttrib == 0 && (& dwAttrib the FILE_ATTRIBUTE_DIRECTORY);!
}
// determines whether there is a folder
BOOL IsDirExist (const CString & csDir)
{
    DWORD = dwAttrib the GetFileAttributes (csDir);
    ! && dwAttrib return INVALID_FILE_ATTRIBUTES = 0 = (& dwAttrib the FILE_ATTRIBUTE_DIRECTORY);!
}
// determines whether there is a file or folder
BOOL IsPathExist (const CString & csPath)
{
    DWORD = dwAttrib the GetFileAttributes (csPath);
    ! = dwAttrib INVALID_FILE_ATTRIBUTES return;
}

/ / Tsuburi variant variant (a little faster heard), see Remarks. 1
BOOL IsPathExist (const CString & csPath)
{
    WIN32_FILE_ATTRIBUTE_DATA attrs = {0};
    ! = 0 return GetFileAttributesEx (csPath, GetFileExInfoStandard, & attrs);
}


cruel stream : CreateFile

This world has no shortage of ruthless people, the programmer community as well. Because of the powerful APICreateFile OPEN_EXISTING configured such that it can be used to present a file or folder determined in NO. External links but the documentation and dozens of thousands of its eloquent words, all the programmer to explicitly declare: I have a lot of pits, you dare to step on it? Declaration sentence will deter many people, in addition to ruthless people. These ruthless people put a lot of explanatory text and external links all carcasses destroyed, eventually extracted a chain of rules - it's the file, and then use in the project. But if one thing is not careful, the chain will break this rule, BUG devil will come! So, this genre disciples, both for the project or on their own, are called cruel! Therefore, the following is not responsible for the correctness of the function I (I even dare cross my mechanical keyboard swear, it certainly is not true)! ! ! Code as follows:

// whether a file or folder exists
BOOL IsPathExist (const CString & csPath)
{
    HANDLE hFile = CreateFile (
        csPath // To determine the file or folder
        0, // we need only minimal privileges to
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, // we do not have any files occupy
        NULL, // security attributes, we do not care
        OPEN_EXISTING, // only open an existing file, it is our goal
        FILE_ATTRIBUTE_NORMAL, // default
        NULL // no
    );
    IF (! == INVALID_HANDLE_VALUE hFile && (ERROR_ACCESS_DENIED = GetLastError ()))
    {
        return FALSE;
    }

    IF ( ! = INVALID_HANDLE_VALUE hFile)
    {
        the CloseHandle (hFile); // here we must close the file handle, or will cause files occupy and resource leaks.
        = INVALID_HANDLE_VALUE hFile;
    }
    return TRUE;
}

   

classical flow: _access

Some people like the new, naturally, it was nostalgia. Some programmers with a classical sensibility, and insisted on finding a pure land as a C library functions in the Windows API on the site. So in a pile hump variable and function names among the neat low-key _access defend their dignity in silence. Nothing to say, tribute, on the code:

// determines whether there is a file or folder
BOOL IsPathExist (const CString & csPath)
{
    int = nRet _taccess (csPath, 0);
    return 0 == == EACCES nRet || nRet;
}

  

delicate flow: FindFirstFile

when rookie just leave home wherever they went, always naive, innocent, they founded the sect is delicate. FindFirstFile to Find and First coincident with the heart and started his exploration of the meaning rookie to win their favor. But in practical application, it was easy to defeat the big devil BUG: its parameters can not be by the end of \, it can not determine the root correctly, code complexity. Code as follows:

// determines whether a file exists
BOOL IsFileExist (const CString & csFile)
{
    IF (csFile.IsEmpty ())
        return FALSE;

    BOOL bEndOfSlash = (_T ( '\\') == csFile.GetAt (csFile.GetLength ( ) -. 1) || _T ( '/') == csFile.GetAt (csFile.GetLength () -. 1));
    IF (bEndOfSlash)
        return FALSE;

    WIN32_FIND_DATA fd = { 0 };
    HANDLE hFind = FindFirstFile(csFile, &fd);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        return FALSE;
    }

    FindClose(hFind);
    hFind = INVALID_HANDLE_VALUE;
    return 0 == (FILE_ATTRIBUTE_DIRECTORY & fd.dwFileAttributes);
}
// 判断文件夹是否存在
BOOL IsDirExist(const CString & csDir)
{
    if (csDir.IsEmpty())
        return FALSE;

    BOOL bEndOfSlash = (_T('\\') == csDir.GetAt(csDir.GetLength() - 1) || _T('/') == csDir.GetAt(csDir.GetLength() - 1));
    CString csFind = csDir + (bEndOfSlash ? _T("*") : _T("\\*"));

    WIN32_FIND_DATA fd = { 0 };
    = HFind the FindFirstFile HANDLE (csFind, FD &);
    IF (INVALID_HANDLE_VALUE == hFind)
    {
        return FALSE;
    }

    FindClose (hFind);
    hFind = INVALID_HANDLE_VALUE;
    ! = 0 return (the FILE_ATTRIBUTE_DIRECTORY & fd.dwFileAttributes);
}

// file or Analyzing folder exists
BOOL IsPathExist (const CString & csPath)
{
    return IsFileExist (csPath) || IsDirExist (csPath);
}


uninhibited flow: PathFileExists

life is short, let a Jinzun empty of the month, they must not focusing instead on writing code. Disciples of this genre, things to do like, a little side effects does not matter, and that time might as well have a good time too! So they chose PathFileExists. The encapsulated by an authority API really gives a sense of security, but it is uncomfortable, it requires us to rely on additional Shlwapi.dll. Just for a API, worth it? Some people in meditation, but some people have already given the answer. Code as follows:

// determines whether there is a file or folder
BOOL IsPathExist (const CString & csPath)
{
    PathFileExists return (csPath);
}


seek death Flow: DeleteFile / RemoveDirectory

programmer is a complete circle of the biosphere, biodiversity is of great guarantee. So there is a genre that we must not ignore, it is that: seek death stream! Seek death disciple stream, the meaning of life lies to die, bring some unexpected way to other people, perhaps even contributed to some of the butterfly effect it! On the Windows platform, they succeeded with the established facts tell you that a file or folder in the end exists. Code as follows:

// determines whether a file exists
BOOL IsFileExist (const CString & csFile)
{
    IF (the DeleteFile (csFile))
    {
        return FALSE; // do not really exist, oh!
    }
    Return ERROR_ACCESS_DENIED the GetLastError == ();
}
// determines whether there is a folder
BOOL IsDirExist (const CString & csDir)
{
    IF (RemoveDirectory (csDir))
    {
        return FALSE; // Barbara does not exist!
    }
    == ERROR_ACCESS_DENIED the GetLastError return () || ERROR_DIR_NOT_EMPTY the GetLastError == ();
}
// determines whether there is a file or folder
BOOL IsPathExist (const CString & csPath)
{
    return IsFileExist (csPath) || IsDirExist (csPath);
}

summarized

above genre, advantages and disadvantages. List is as follows:
Genre support XP can identify files and folders have additional dependencies of code to determine the degree of difficulty known case of an error (otherwise it does not mean necessarily correct)
Avenue stream Yes Yes Easy network share (to be specified subfolder network share folder)
brutal stream is difficult to root directory such as "C: \", but "C: /"! this is possible - -
classical flow is easily no
Delicate flow is a difficult No
uninhibited flow is easy to Shlwapi.dll UNC path to the specified folder (the file can)
seek death stream is that I did not dare try ● - ●

However, I do not believe that these schools is that this party all the lakes. I believe some people know not the place, there must be some hidden sect, an ancient family, every minute can kill these schools. Please also insider told me!
Notes

    Note 1: See judgment about whether a file exists the most efficient function. https://blog.csdn.net/dragoo1/article/details/44492239
----------------

Original link: https: //blog.csdn.net/u012494876/article/ details / 51204615

Guess you like

Origin www.cnblogs.com/htj10/p/11567022.html