常见的C文件操作,读取,写入,获取文件指针

来源:互联网 发布:淘宝开手机店保证金 编辑:程序博客网 时间:2024/06/05 23:29

近用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.html



原创粉丝点击