在使用C++进行系统开发时,经常用到对文件进行操作的方法,比如判断文件是否存在、获得文件的大小和创建时间等等。下面是我写的一个关于文件操作的类,里面不含有文件读写操作,只含有文件的外围操作。如果读者需要添加文件的读写操作,可以在类里面添加方法,使用文件流操作fstream进行读写。
编译和运行环境是在VC++6.0,File.h如下:
InBlock.gif#ifndef _FILE_H
InBlock.gif#define _FILE_H
InBlock.gif
#include < string>
InBlock.gif
namespace zpp
InBlock.gif{
InBlock.gif class File {
InBlock.gif   private:
InBlock.gif    std:: string fileName;
InBlock.gif
   public:
InBlock.gif    File( const std:: string& aFileName);
InBlock.gif    ~File();
InBlock.gif
     bool exist();
InBlock.gif     bool isDirectory();
InBlock.gif
     long getFileSize();
InBlock.gif     char getFileDrive();
InBlock.gif    std:: string getCreateTime();
InBlock.gif    std:: string getModifiedTime();
InBlock.gif  };
InBlock.gif}
InBlock.gif
#endif
File.cpp文件如下:
InBlock.gif#include <File.h>
InBlock.gif#include <sys/stat.h>
InBlock.gif#include <time.h>
InBlock.gif
namespace zpp
InBlock.gif{
InBlock.gif  File::File( const std:: string& aFileName):fileName(aFileName) {
InBlock.gif  
InBlock.gif  }
InBlock.gif
  File::~File() {
InBlock.gif  
InBlock.gif  }
InBlock.gif
   bool File::exist() {
InBlock.gif     struct _stat buf;
InBlock.gif     int result;
InBlock.gif    result = _stat(fileName.c_str(), &buf);
InBlock.gif     return (result == 0);
InBlock.gif  }
InBlock.gif
   bool File::isDirectory() {
InBlock.gif     struct _stat buf;
InBlock.gif     if ( _stat(fileName.c_str(), &buf) != 0 ) {     //判断是否存在
InBlock.gif       return false;
InBlock.gif    }
InBlock.gif     return ( (buf.st_mode & S_IFDIR) !=0 );
InBlock.gif  }
InBlock.gif
   long File::getFileSize() {
InBlock.gif     struct _stat buf;
InBlock.gif     int result;
InBlock.gif    result = _stat(fileName.c_str(), &buf);
InBlock.gif     if ( result == 0 ) {
InBlock.gif       return buf.st_size;
InBlock.gif    }
InBlock.gif     return 0;
InBlock.gif  }
InBlock.gif
   char File::getFileDrive() {
InBlock.gif     struct _stat buf;
InBlock.gif     int result;
InBlock.gif    result = _stat(fileName.c_str(), &buf);
InBlock.gif     if ( result == 0 ) {
InBlock.gif       return ( buf.st_dev + 'A' );
InBlock.gif    }
InBlock.gif     return '0';
InBlock.gif  }
InBlock.gif
  std:: string File::getCreateTime() {
InBlock.gif     struct _stat buf;
InBlock.gif     int result;
InBlock.gif    result = _stat(fileName.c_str(), &buf);
InBlock.gif     if ( result == 0 ) {
InBlock.gif       return std:: string( ctime(&buf.st_ctime) );
InBlock.gif    }
InBlock.gif     return "0";
InBlock.gif  }
InBlock.gif
  std:: string File::getModifiedTime() {
InBlock.gif     struct _stat buf;
InBlock.gif     int result;
InBlock.gif    result = _stat(fileName.c_str(), &buf);
InBlock.gif     if ( result == 0 ) {
InBlock.gif       return std:: string( ctime(&buf.st_atime) );
InBlock.gif    }
InBlock.gif     return "0";
InBlock.gif  }
InBlock.gif}