判断文件是否存在

#include using namespace std;

// 方法一:使用fstream的is_open()函数判断文件是否存在 ifstream fin; fin.open(“filename”); if( fin.is_open() ) cout << “File exists” << endl; else cout << “Error! File does not exist” << endl; fin.close();

// 方法二:使用ifstream构造函数判断文件是否存在 ifstream fin(“filename”); if( fin ) cout << “File exists” << endl; else cout << “Error! File does not exist” << endl;

C++ 文件是否存在可以使用c++内置的 < fstream > 头文件来判断:

#include <fstream>      
using namespace std;    

int main(){ 
 
  ifstream file("filename.txt");  //filename.txt 是你要检查的文件
  
  if(file){  				     //如果文件存在,返回true
    cout << "File exist." << endl; 
  }
  else {  					     //如果文件不存在,返回false
    cout << "File does not exist." << endl;
  }
 
  return 0;
}

若要判断文件是否存在,可以使用 Linux 中的 access() 函数,其原型为:

int access(const char *pathname, int mode);

其中pathname 是指定文件的路径,mode可以是F_OK,表示判断文件是否存在;mode也可以是执行权的判断方式,比如R_OK,表示有读取文件的权限;还有W_OK、X_OK等权限判断方式,具体的可以查看access的Linux的man文档;

C++ 可以使用 <sys/stat.h> 头文件中的stat()函数进行文件的判断,其原型为:

int stat(const char *file_name, struct stat *buf);

参数file_name表示文件名,buf参数用于存储该文件信息,如果文件存在,该函数会返回一个零值;其中可以使用buf->st_mode == S_IFREG 判断,若结果为true,则说明这是一个普通文件;另外buf->st_mode == NULL 也可以判断文件是否存在,若返回值为true,则表示文件不存在;

#include <string>
#include <fstream>

bool FileExists(const std::string& FileName)
{
    std::ifstream file(FileName);
    return file.good();
}
#include <iostream>
#include<string>
#include <fstream>
using namespace std;
int main()
{
    string fileName;
    cout<<"请输入要判断的文件路径:";
    cin>>fileName;  
    ifstream file(fileName);  
    if (file) 
        cout<<"文件存在"<<endl;  
    else
        cout<<"文件不存在"<<endl;  
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值