本文中写了两个函数:oracle
1)int IsFileExist(const char* path)函数
用于检查一个目录是否存在 -1:存在 0:不存在spa
2)int IsFileExist(const char* path)code
用于检查文件(全部类型,包括目录类型)是否存在 -1:存在 0:不存在string
若是不存在,能够用如下两种方式打印错误信息:io
1)fprintf(stderr, "ERROR: %s\n", strerror(errno));class
2)perror("ERROR");sed
程序代码:程序
#include <stdio.h> #include <dirent.h> #include <unistd.h> #include <sys/stat.h> #include <string.h> #include <errno.h> //检查目录是否存在 //-1:存在 0:不存在 int IsFolderExist(const char* path) { DIR *dp; if ((dp = opendir(path)) == NULL) { return 0; } closedir(dp); return -1; } //检查文件(全部类型)是否存在 //-1:存在 0:不存在 int IsFileExist(const char* path) { return !access(path, F_OK); } // void Display(const char *path) { if (IsFolderExist(path)) { printf("Folder [%s] Exist!\n", path); } else { printf("Folder [%s]\n", path); //捕获errno方法1: fprintf fprintf(stderr, "ERROR: %s\n", strerror(errno)); } if(IsFileExist(path)) { printf("File [%s] Exist!\n", path); } else { printf("File [%s]\n", path); //捕获error方法2: perror perror("ERROR"); } } int main() { Display("/home/oracle/Documents"); //Current Folder Display("/home/12345edcba"); //Folder Not Exist Display("/home/oracle/Documents/a.c"); //Existing File return 0; }
运行截图:方法
END