灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:3418回复:0

[C++技术]C++基础:怎样判断某一文件是否存在

楼主#
更多 发布于:2011-12-27 11:56

很简单的一种办法:

#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "stat.dat"
int main()
{
     fstream _file;
     _file.open(FILENAME,ios::in);
     if(!_file)
     {
         cout<<FILENAME<<"没有被创建";
      }
      else
      {
          cout<<FILENAME<<"已经存在";
      }
      return 0;
}



另外一种利用 c 语言的库的办法:

函数名: access
功  能: 确定文件的访问权限
用  法: int access(const char *filename, int amode);
程序例:
#include <stdio.h>
#include <io.h>

int file_exists(char *filename);

int main(void)
{
  printf("Does NOTEXIST.FIL exist: %s\n",
  file_exists("NOTEXISTS.FIL") ? "YES" : "NO");
  return 0;
}

int file_exists(char *filename)
{
  return (access(filename, 0) == 0);
}



access(filename, 0)0 表示判断文件是否存在

finename 文件名称                                      mode 模式,共5种模式:                                

0-检查文件是否存在        

1-检查文件是否可运行        

2-检查文件是否可写访问    

4-检查文件是否可读访问    

6-检查文件是否可读/写访问

喜欢0 评分0
游客

返回顶部