织梦CMS - 轻松建站从此开始!

罗索

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

jackyhwei 发布于 2010-11-04 11:10 点击:次 
下面是我写的一个关于文件操作的类,里面不含有文件读写操作,只含有文件的外围操作。如果读者需要添加文件的读写操作,可以在类里面添加方法,使用文件流操作fstream进行读写。
TAG:

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

File.h如下:

  1. #ifndef _FILE_H 
  2. #define _FILE_H 
  3.  
  4. #include <string> 
  5.  
  6. namespace zpp 
  7. class File { 
  8.   private
  9.     std::string fileName; 
  10.  
  11.   public
  12.     File(const std::string& aFileName); 
  13.     ~File(); 
  14.  
  15.     bool exist(); 
  16.     bool isDirectory(); 
  17.  
  18.     long getFileSize(); 
  19.     char getFileDrive(); 
  20.     std::string getCreateTime(); 
  21.     std::string getModifiedTime(); 
  22.   }; 
  23.  
  24. #endif 

File.cpp文件如下:

  1. #include <File.h> 
  2. #include <sys/stat.h> 
  3. #include <time.h> 
  4.  
  5. namespace zpp 
  6.   File::File(const std::string& aFileName):fileName(aFileName) { 
  7. File::~File() {} 
  8. bool File::exist() { 
  9.     struct _stat buf; 
  10.     int result; 
  11.     result = _stat(fileName.c_str(), &buf); 
  12.     return (result == 0); 
  13.   } 
  14.  
  15.   bool File::isDirectory() { 
  16.     struct _stat buf; 
  17.     if ( _stat(fileName.c_str(), &buf) != 0 ) {    //判断是否存在 
  18.       return false
  19.     } 
  20.     return ( (buf.st_mode & S_IFDIR) !=0 ); 
  21.   } 
  22.  
  23.   long File::getFileSize() { 
  24.     struct _stat buf; 
  25.     int result; 
  26.     result = _stat(fileName.c_str(), &buf); 
  27.     if ( result == 0 ) { 
  28.       return buf.st_size; 
  29.     } 
  30.     return 0; 
  31.   } 
  32.  
  33.   char File::getFileDrive() { 
  34.     struct _stat buf; 
  35.     int result; 
  36.     result = _stat(fileName.c_str(), &buf); 
  37.     if ( result == 0 ) { 
  38.       return ( buf.st_dev + 'A' ); 
  39.     } 
  40.     return '0'
  41.   } 
  42.  
  43.   std::string File::getCreateTime() { 
  44.     struct _stat buf; 
  45.     int result; 
  46.     result = _stat(fileName.c_str(), &buf); 
  47.     if ( result == 0 ) { 
  48.       return std::string( ctime(&buf.st_ctime) ); 
  49.     } 
  50.     return "0"
  51.   } 
  52.  
  53.   std::string File::getModifiedTime() { 
  54.     struct _stat buf; 
  55.     int result; 
  56.     result = _stat(fileName.c_str(), &buf); 
  57.     if ( result == 0 ) { 
  58.       return std::string( ctime(&buf.st_atime) ); 
  59.     } 
  60.     return "0"
  61.   } 

来自:http://panpan.blog.51cto.com/489034/102625/

(panpan)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201011/10406.html]
本文出处:panpan.blog.51cto.com 作者:panpan
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容