c语言文件大小获取

转:使用c函数获取文件大小

(2011-03-25 17:41:37)
标签:

杂谈

分类: c_Study
取得当前文件指针位置函数:
 long ftell(FILE *stream );
如果文件指针位于文件尾,则取得了文件大小。
 int fseek(FILE *stream,long offset,int origin );
stream:Pointer to FILE structure. 
 offset:Number of bytes from origin.
 origin:Initial position. 可以取下面的值
 
SEEK_CUR:Current position of file pointer. SEEK_END:End of file. SEEK_SET:Beginning of file. 例如:取一个文件大小: //传入使用fopen打开的文件结构指针 File     int currentPos = ftell(File); //取得当前文件指针位置,可能已经移动了文件指针
    fseek(File, 0, SEEK_END);//移动到文件的结尾
    int lastPos = ftell(File);//获得文件大小
    fseek(File,currentPos,SEEK_SET);//恢复到原来的文件指针位置
    return lastPos;
如果文件大于 4G ,就要用64 位的 __int64 _ftelli64(  FILE *stream );
删除文件可以使用函数: int _unlink(const char * filename ); 
获取当前路径是: char *_getcwd(char * buffer  int maxlen );

如果文件大于 4G ,就要用64 位的 __int64 _ftelli64(  FILE *stream );

近用c语言做文件操作比较频繁,记几个常用的操作

获得文件大小:

fseek(fp, 0, SEEK_END);
int fileSize = ftell(fp);
rewind(fp);

读取指定位置的数据块:

fseek( fp,offset,SEEK_SET );
int num_read = fread(buf, 1, length, fp);

删除文件

int res = access( filename,0 ); // 判断文件是否存在
if ( res == 0 )
{
   res = remove( filename );// 删除文件
   return ( res ==0 );
}

在指定位置写入块数据:

fseek( fp, offset, SEEK_SET );
num_write = fwrite( buf, 1, n, fp );

打开文件方式中有一个比较特别的,如果某文件中已经有了一部分数据,你需要继续在上面添加数据,但是是在指定位置添加,也就是说,仍然需要通过 fseek 找到写入位置,然后再 fwrite,这时候需要以 "rb+" 方式打开。而不能以"a"或者"ab+"方式。以"a"方式打开,fseek函数不起作用。

获得文件属性

struct stat st;
   FILE *fp = fopen( filename.c_str(),"rb" );
   if ( !fp )
   { // error
   }
   fstat( fp->_file, &st );

遍历目录

std::string dirspec = dir + "\\*.*";
struct _finddata_t filefind;
int done = 0;
intptr_t handle = 0;

if( ( handle = _findfirst(dirspec.c_str(),&filefind) ) == -1 )
   return IVS_FAIL;

IVS_RESULT res = IVS_OK, response =IVS_OK;
while( !(done=_findnext(handle,&filefind)) )  
 
   if( !strcmp(filefind.name,"..") || !strcmp(filefind.name,".") )
    continue;  

   AdsFileInfo info;
   if((_A_SUBDIR==filefind.attrib))  
               
    info._filename = filefind.name;
    info._fileSize = filefind.size;
    info._atime = filefind.time_access;
    info._ctime = filefind.time_create;
    info._mtime = filefind.time_write;
    info._isdir = true;
   
   else    
   
    std::string tmpFilename = dir + "\";
    tmpFilename += filefind.name;
    res = getFileInfo( tmpFilename, info );
    response = (!SUCCESS(res))?res: response;
   }
   list.push_back( info );
         
_findclose(handle);  

http://hi.baidu.com/wangleitongxing/blog/item/5ca7350e69a529236159f337

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值