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

短命女 2022-06-10 10:47 1635阅读 0赞

判断文件是否存在

  1. ifstream

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

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

用File来判断文件是否存在

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

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

  1. #include <io.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int main( void )
  5. {
  6. // Check for existence.
  7. if( (_access( "crt_ACCESS.C", 0 )) != -1 )
  8. {
  9. printf_s( "File crt_ACCESS.C exists.\n" );
  10. // Check for write permission.
  11. // Assume file is read-only.
  12. if( (_access( "crt_ACCESS.C", 2 )) == -1 )
  13. printf_s( "File crt_ACCESS.C does not have write permission.\n" );
  14. }
  15. }

判断文件夹是否存在

  1. _stat() (linux中为stat())

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

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

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

  1. GetFileAttributesA()

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

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

参考:

  1. 关于C++中如何判断文件,目录存在的若干方法
  2. C++ - 判断文件夹(folder)是否存在(exist)
  3. Linux C编程—目录文件操作

发表评论

表情:
评论列表 (有 0 条评论,1635人围观)

还没有评论,来说两句吧...

相关阅读