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

在使用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();
  };
}

#endif
File.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";
  }
}

你可能感兴趣的:(C++,大小,文件,休闲,存在)