加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中检查文件是否存在

发布时间:2020-12-16 09:29:46 所属栏目:百科 来源:网络整理
导读:目前我使用的东西如下: #include sys/stat.h#include "My_Class.h"void My_Class::my_function(void){ std::ofstream my_file; struct stat file_info; if ( filename_str.compare("")!=0 stat(filename_str.c_str(),file_info) == 0 ) { my_file.open(file
目前我使用的东西如下:

#include <sys/stat.h>

#include "My_Class.h"

void My_Class::my_function(void)
{
  std::ofstream my_file;

  struct stat file_info; 

  if ( filename_str.compare("")!=0  &&
       stat(filename_str.c_str(),&file_info) == 0 )
  {
    my_file.open(filename_str.data(),std::ios::trunc);
    //do stuff
    my_file.close(); 
  }
  else if ( filename_str.compare("")==0 )
  {
    std::cout << "ERROR! ... output filename not assigned!" << std::endl;
  }
  else
  {
    std::cout << "ERROR! File :" << std::endl
          << filename_str << std::endl 
          << "does not exist!!" << std::endl;
  }
}

……这是一个不错的方式,还是有更好的选择?如果我没有读取文件的权限,似乎我可以运行任何权限.

这不是一个功课,问题,这是一个关于最佳实践的问题.

解决方法

一般来说,我认为最好只是尝试打开它并发现错误.

IMO,检查权限是不明智的,因为如果它是一个Linux框并且你检查它的属性,决定你不能写它,但文件系统支持ACL,他们确实授予你权限? (作为系统管理员,我无法忍受应用程序执行此操作.我喜欢ACL,如果您是应用程序,请不要告诉我除非您先尝试过,否则无法写入文件.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读