判断文件是否存在
- ifstream
用ifstream创建文件的输入流,如果文件不存在,则输入流创建失败。
ifstream fin("hello.txt"); if(!fin){ //TODO }
- File
用File来判断文件是否存在
File *fh = fopen("hello.txt","r"); if(fh == NULL){ //TODO }
- _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" ); } }
判断文件夹是否存在
- _stat() (linux中为stat())
int _stat(const char* path, struct _stat* buffer);
int _stat((dir.c_str(), &fileStat) == 0)&& (fileStat.st_mode & _S_IFDIR)){ //TODO }
其中_S_IFDIR是个标志位,为目录改为就会被系统设置
- 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! }
参考: