1.fseek ftellfseek(移动文件流的读写位置)
#include
int fseek(FILE * stream,long
offset,int whence);
参数stream为已打开的文件指针,参数offset为根据参数whence来移动读写位置的位移数。
参数 whence为下列其中一种:
SEEK_SET从距文件开头offset位移量为新的读写位置。SEEK_CUR 以目前的读写位置往后增加
offset个位移量。
SEEK_END将读写位置指向文件尾后再增加offset个位移量。
当whence值为SEEK_CUR 或SEEK_END时,参数offset允许负值的出现。
下列是较特别的使用方式:
1) 欲将读写位置移动到文件开头时:fseek(FILE *stream,0,SEEK_SET);
2) 欲将读写位置移动到文件尾时:fseek(FILE *stream,0,SEEK_END);
返回值 当调用成功时则返回0,若有错误则返回-1,errno会存放错误代码。
附加说明 fseek()不像lseek()会返回读写位置,因此必须使用ftell()来取得目前读写的位
置。
ftell(取得文件流的读取位置)
#include
long ftell(FILE * stream);
ftell()用来取得文件流目前的读写位置。参数stream为已打开的文件指针。
当调用成功时则返回目前的读写位置,若有错误则返回-1,errno会存放错误代码。
错误代码 EBADF 参数stream无效或可移动读写位置的文件流。
取得文件长度的主要代码如下:
FILE *fp = fopen(filename,
"r");
fseek(fp, 0, SEEK_END);
long filelength = ftell(fp);
这里的filelength就是名为filename的文件的长度。
2.fileno lseek
fileno是将一个FILE*类型的文件流指向的文件的文件描述符返回:int fileno(FILE
*)
lseek(移动文件的读写位置)
#include
#include
off_t lseek(int fildes,off_t offset ,int whence);
取得文件长度的主要代码如下:
FILE
*fp = fopen(filename, "r");
int
handle = fileno(fp);
long filelength = lseek(handle, 0,
SEEK_END);
这里的filelength就是名为filename的文件的长度。
windows
系统中有filelength函数
long _filelength(
int fd
);
__int64 _filelengthi64(
int fd
);
fd: Target the file descriptor.