取得当前文件指针位置函数:
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
|