C/C++编程:判断文件是否存在

妖狐艹你老母 2022-12-21 14:52 306阅读 0赞

使用access

  1. /*
  2. __name 文件名
  3. __type 模式:
  4. 0-检查文件是否存在
  5. 1-检查文件是否可运行
  6. 2-检查文件是否可写访问
  7. 4-检查文件是否可读访问
  8. 6-检查文件是否可读/写访问
  9. */
  10. int access (const char *__name, int __type)
  11. #include <stdio.h>
  12. bool file_exists(const char *filename)
  13. {
  14. return (access(filename, 0) == 0);
  15. }
  16. int main()
  17. {
  18. const char * filename = "/usr/lib64/mysql/libmysqlclient_r.so";
  19. printf("Does NOTEXIST.FIL exist: %s\n",file_exists(filename) ? "YES" : "NO");
  20. return 0;
  21. }

第二种方法

  1. #include <unistd.h>
  2. #include <string>
  3. #include <fstream>
  4. using namespace std;
  5. inline bool file_exists(const char * name) {
  6. ifstream f(name);
  7. return f.good();
  8. }
  9. int main()
  10. {
  11. const char * filename = "/usr/lib64/mysql/libmysqlclient_r.so";
  12. printf("Does NOTEXIST.FIL exist: %s\n",file_exists(filename) ? "YES" : "NO");
  13. return 0;
  14. }

发表评论

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

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

相关阅读