失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > linux下文件或目录是否存在的函数 Linux下的C++程序:判断目录/文件是否存在

linux下文件或目录是否存在的函数 Linux下的C++程序:判断目录/文件是否存在

时间:2024-04-08 10:29:51

相关推荐

linux下文件或目录是否存在的函数 Linux下的C++程序:判断目录/文件是否存在

本文中写了两个函数:

1)int IsFileExist(const char* path)

用于检查一个目录是否存在 -1:存在 0:不存在

2)int IsFileExist(const char* path)

用于检查文件(所有类型,包括目录类型)是否存在 -1:存在 0:不存在

如果不存在,可以用以下两种方式打印错误信息:

1)fprintf(stderr, "ERROR: %s\n", strerror(errno));

2)perror("ERROR");

程序代码:

#include

#include

#include

#include

#include

#include

//检查目录是否存在

//-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

如果觉得《linux下文件或目录是否存在的函数 Linux下的C++程序:判断目录/文件是否存在》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。