谷动谷力

 找回密码
 立即注册
查看: 64|回复: 0
打印 上一主题 下一主题
收起左侧

【C/C++】C/C++语言判断文件是否存在的方法浅析

[复制链接]
跳转到指定楼层
楼主
发表于 2024-4-1 16:04:25 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
【C/C++】C/C++语言判断文件是否存在的方法浅析


1. 方法一:C语言之access

可以使用C语言中unistd.h里的函数access()来判断文件是否存在,其原型如下:
  1. int access(const char *filename, int mode);
复制代码


filename是文件名,mode有下列几种方法:

mode        Description
F_OK        测试文件是否存在
R_OK        测试文件是否有读权限
W_OK        测试文件是否有写权限
X_OK        测试文件是否有执行权限
返回0,表示存在(成功),返回非0表示不存在(错误)。

使用方法
  1. #include <unistd.h>
  2. #include <stdio.h>

  3. int main(void)
  4. {
  5.     if (access("test.txt", F_OK) == 0)
  6.     {
  7.         printf("test.txt exists.\n");
  8.     }
  9.     else
  10.     {
  11.         printf("test.txt not exists.\n");
  12.     }
  13.     return 0;
  14. }
复制代码


2. 方法二:C++方法之ifstream
ifstream中的good方法可以判断一个文件是否存在。
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. using namespace std;

  5. bool isFileExists_ifstream(string& name) {
  6.     ifstream f(name.c_str());
  7.     return f.good();
  8. }
  9. int main()
  10. {
  11.     string filename = "test.txt";

  12.     bool ret = isFileExists_ifstream(filename);
  13.     if (ret)
  14.     {
  15.         cout << "test.txt存在" << endl;
  16.     }
  17.     else
  18.     {
  19.         cout << "test.txt不存在" << endl;
  20.     }
  21. }
复制代码

3. 方法三:fopen方法


可以使用fopen的方式尝试打开一个文件。
  1. #include <iostream>
  2. #include <stdio.h>
  3. using namespace std;

  4. bool isFileExists_fopen(string& name) {
  5.     if (FILE *file = fopen(name.c_str(), "r")) {
  6.         fclose(file);
  7.         return true;
  8.     } else {
  9.         return false;
  10.     }   
  11. }

  12. int main()
  13. {
  14.     string filename = "test.txt";

  15.     bool ret = isFileExists_fopen(filename);
  16.     if (ret)
  17.     {
  18.         cout << "test.tx存在" << endl;
  19.     }
  20.     else
  21.     {
  22.         cout << "test.tx不存在" << endl;
  23.     }
  24. }
复制代码

4. 方法四:sys中的stat函数方法

sys中的stat函数可以查阅文件的状态。
  1. #include <iostream>
  2. #include <sys/stat.h>
  3. using namespace std;

  4. bool isFileExists_stat(string& name) {
  5.   struct stat buffer;   
  6.   return (stat(name.c_str(), &buffer) == 0);
  7. }

  8. int main()
  9. {
  10.     string filename = "test.tx";

  11.     bool ret = isFileExists_stat(filename);
  12.     if (ret)
  13.     {
  14.         cout << "test.tx存在" << endl;
  15.     }
  16.     else
  17.     {
  18.         cout << "test.tx不存在" << endl;
  19.     }
  20. }
复制代码


+10
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|深圳市光明谷科技有限公司|光明谷商城|Sunshine Silicon Corpporation ( 粤ICP备14060730号|Sitemap

GMT+8, 2024-5-5 06:46 , Processed in 0.102096 second(s), 40 queries .

Powered by Discuz! X3.2 Licensed

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表