记几个常见的c文件操作

近用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);  

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值