C语言用fstat函数获取文件的大小
来源:文书网 2.02W
C语言用fstat函数获取文件的大小。之前获取文件大小总是用死办法,open一个文件,然后lseek,read这样去获取文件的大小,这样的效率实在是低,还有可能粗心大意还会出错。下面一起跟着小编来学习一下吧!
一次偶然在Android的源代码中看到获取文件大小的函数,在以下范例中。用fstat这个函数可以避免这些问题。
函数原型:int fstat(int fildes, struct stat *buf);
参数说明:
fstat()用来将参数fildes所指的.文件状态,复制到参数buf所指的结构中(struct stat)。
写个范例:
123456789101112131415161718192021222324252627 | #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys stat.h= "" > #include <unistd.h> //获取文件的大小 int get_file_size( int f) {
struct stat st;
fstat(f, &st);
return _size; } int main( void ) {
int fd = open( "" ,O_RDWR);
int size ;
if (fd < 0 )
{
printf( "open fair!" );
return - 1 ;
}
size = get_file_size(fd) ;
printf( "size:%d字节--->%.2fK" ,size,( float )size/ 1024 );
return 0 ; }</unistd.h></sys></fcntl.h></stdlib.h></stdio.h> |