How to determine the existence of a file or directory in C and C++

  • 2020-04-02 01:06:49
  • OfStack

1. A simple C++ solution:

#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "stat.dat"
int main()
{
     fstream _file;
     _file.open(FILENAME,ios::in);
     if(!_file)
     {
         cout<<FILENAME<<" Not created ";
      }
      else
      {
          cout<<FILENAME<<" existing ";
      }
      return 0;
}

2. Ways to make use of the library of c language:
Function name: access
work   Can: determine the file access rights
with   Int access(const char *filename, int amode);
This function has never been used before, today the debugger found this function, feel good, especially to determine whether a file or folder exists, do not need to find, the file can also detect read and write permissions, folder can only determine whether there is, the following excerpt from MSDN:
Int _access(const char *path, int mode);
The Return Value
Each of these functions returns 0 if the file has the given mode. The function returns 1 if the named file does not exist or is not accessible in the given mode; In this case, errno is set as follows:
EACCES
Permission: file's permission setting does not allow specified Access.
ENOENT
Filename or path not found.
The Parameters
The path
The File or directory path
mode
The Permission setting
few
When used with files, the _access function determines whether the specified file exists and can be handled as specified by the value of mode. _access determines only whether the specified directory exists; In Windows NT, all directories have read and write access.
Mode the Value                       Checks the File For
00                                                           Existence only
02                                                           The Write permission
04                                                           The Read permission
06                                                           The Read and write permission
Example


#include  <io.h>
#include  <stdio.h>
#include  <stdlib.h>
void main( void )
{
   
   if( (_access( "ACCESS.C", 0 )) != -1 )
   {
      printf( "File ACCESS.C exists " );
      
      if( (_access( "ACCESS.C", 2 )) != -1 )
         printf( "File ACCESS.C has write permission " );
   }
}

OutputFile access. C existsFile access. C has write permission
3. Using API function FindFirstFile(...) on Windows platform :
(1) check whether the file exists:

#define _WIN32_WINNT 0x0400
#include "windows.h"
int
main(int argc, char *argv[])
{
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;
  printf ("Target file is %s. ", argv[1]);
  hFind = FindFirstFile(argv[1], &FindFileData);
  if (hFind == INVALID_HANDLE_VALUE) {
    printf ("Invalid File Handle. Get Last Error reports %d ", GetLastError ());
  } else {
    printf ("The first file found is %s ", FindFileData.cFileName);
    FindClose(hFind);
  }
  return (0);
}

(2) check whether a directory exists:

/// check whether the directory exists:
bool  CheckFolderExist(const string &strPath)
{
    WIN32_FIND_DATA  wfd;
    bool rValue = false;
    HANDLE hFind = FindFirstFile(strPath.c_str(), &wfd);
    if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    {
        rValue = true;   
    }
    FindClose(hFind);
    return rValue;
}

4. Exists function for the filesystem library that USES boost

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
int GetFilePath(std::string &strFilePath)
{
    string strPath;
    int nRes = 0;
    //Specify a path & NBSP; & have spent & have spent & have spent & have spent & have spent & have spent & have spent & have spent & have spent & have spent
    strPath = "D:/myTest/Test1/Test2";
    namespace fs = boost::filesystem;
    //Path portability
    fs::path full_path( fs::initial_path() );
    full_path = fs::system_complete( fs::path(strPath, fs::native ) );
    //Determines whether subdirectories at all levels exist, and if they do not, they need to be created
    if ( !fs::exists( full_path ) )
    {
        //Create multi-layer subdirectories
        bool bRet = fs::create_directories(full_path);
        if (false == bRet)
        {
            return -1;
        }
    }
    strFilePath = full_path.native_directory_string();
    return 0;
}

Related articles: