C++文件操作 判断文件是否存在和文件大小

37 篇文章 0 订阅

在使用C++进行系统开发时,经常用到对文件进行操作的方法,比如判断文件是否存在、获得文件的大小和创建时间等等。下面是我写的一个关于文件操作的类,里面不含有文件读写操作,只含有文件的外围操作。如果读者需要添加文件的读写操作,可以在类里面添加方法,使用文件流操作fstream进行读写。

  编译和运行环境是在VC++6.0,File.h如下:

  #ifndef _FILE_H

  #define _FILE_H

  #include <string>

  namespace zpp

  {

  class File {

  private:

  std::string fileName;

  public:

  File(const std::string& aFileName);

  ~File();

  bool exist();

  bool isDirectory();

  long getFileSize();

  char getFileDrive();

  std::string getCreateTime();

  std::string getModifiedTime();

  };

  }

  #endifFile.cpp文件如下:

  #include <File.h>

  #include <sys/stat.h>

  #include <time.h>

  namespace zpp

  {

  File::File(const std::string& aFileName):fileName(aFileName) {

  }

  File::~File() {

  }

  bool File::exist() {

  struct _stat buf;

  int result;

  result = _stat(fileName.c_str(), &buf);

  return (result == 0);

  }

  bool File::isDirectory() {

  struct _stat buf;

  if ( _stat(fileName.c_str(), &buf) != 0 ) {    //判断是否存在

  return false;

  }

  return ( (buf.st_mode & S_IFDIR) !=0 );

  }

  long File::getFileSize() {

  struct _stat buf;

  int result;

  result = _stat(fileName.c_str(), &buf);

  if ( result == 0 ) {

  return buf.st_size;

  }

  return 0;

  }

  char File::getFileDrive() {

  struct _stat buf;

  int result;

  result = _stat(fileName.c_str(), &buf);

  if ( result == 0 ) {

  return ( buf.st_dev + 'A' );

  }

  return '0';

  }

  std::string File::getCreateTime() {

  struct _stat buf;

  int result;

  result = _stat(fileName.c_str(), &buf);

  if ( result == 0 ) {

  return std::string( ctime(&buf.st_ctime) );

  }

  return "0";

  }

  std::string File::getModifiedTime() {

  struct _stat buf;

  int result;

  result = _stat(fileName.c_str(), &buf);

  if ( result == 0 ) {

  return std::string( ctime(&buf.st_atime) );

  }

  return "0";

  }

  }

转自:http://c.chinaitlab.com/example/817028.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值