C语言用fstat函数获取文件的大小

来源:文书网 2.02W

C语言用fstat函数获取文件的大小。之前获取文件大小总是用死办法,open一个文件,然后lseek,read这样去获取文件的大小,这样的效率实在是低,还有可能粗心大意还会出错。下面一起跟着小编来学习一下吧!

C语言用fstat函数获取文件的大小

一次偶然在Android的源代码中看到获取文件大小的函数,在以下范例中。用fstat这个函数可以避免这些问题。

函数原型:int fstat(int fildes, struct stat *buf);

  参数说明:

fstat()用来将参数fildes所指的.文件状态,复制到参数buf所指的结构中(struct stat)。

  写个范例

list-style-type: none; margin: 0px; background-image: none; background-position: 0% 0%; background-size: initial; background-repeat: repeat; background-attachment: scroll; background-origin: initial; background-clip: initial; border-radius: 0px; box-sizing: content-box !important; position: static !important; padding: 0px !important; line-height: 1.1em !important; outline-style: none !important; min-height: auto !important; outline-width: 0px !important; width: auto !important; bottom: auto !important; float: none !important; height: auto !important; font-size: 1em !important; vertical-align: baseline !important; overflow: visible !important; top: auto !important; right: auto !important; left: auto !important;" class="firstRow">
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>

热门标签