C++ 判断文件文件夹是否存在

来源:互联网 发布:tensorflow wordvec 编辑:程序博客网 时间:2024/06/06 03:15

判断文件是否存在

  1. ifstream

用ifstream创建文件的输入流,如果文件不存在,则输入流创建失败。

ifstream fin("hello.txt");  if(!fin){      //TODO  }
  1. File

用File来判断文件是否存在

File *fh = fopen("hello.txt","r");  if(fh == NULL){      //TODO      }
  1. _acess()

int _access( const char *path, int mode );
可以用来查看文件是否存在,是否可写读;仅存在mode为00,可写02,可读04 可读写06;仅在返回0时表示存在或者具有指定特性值;对目录使用时仅表示目录是否存在

#include  <io.h>    #include  <stdio.h>    #include  <stdlib.h>        int main( void )    {        // Check for existence.        if( (_access( "crt_ACCESS.C", 0 )) != -1 )        {            printf_s( "File crt_ACCESS.C exists.\n" );           // Check for write permission.            // Assume file is read-only.            if( (_access( "crt_ACCESS.C", 2 )) == -1 )            printf_s( "File crt_ACCESS.C does not have write permission.\n" );        }    }

判断文件夹是否存在

  1. _stat()

int _stat(const char* path, struct _stat* buffer);

int _stat((dir.c_str(), &fileStat) == 0)&& (fileStat.st_mode & _S_IFDIR)){      //TODO       }

其中_S_IFDIR是个标志位,为目录改为就会被系统设置

  1. GetFileAttributesA()

DWORD d = GetFileAttributesA(const char* filename); #include <windows.h> 为windows系统函数,判断文件目录是否存在

bool dirExists(const std::string& dirName_in)    {        DWORD ftyp = GetFileAttributesA(dirName_in.c_str());        if (ftyp == INVALID_FILE_ATTRIBUTES)             return false;  //something is wrong with your path!        if (ftyp & FILE_ATTRIBUTE_DIRECTORY)            return true;   // this is a directory!        return false;    // this is not a directory!    }

参考:

  1. 关于C++中如何判断文件,目录存在的若干方法
  2. C++ - 判断文件夹(folder)是否存在(exist)
阅读全文
1 0
原创粉丝点击