C语言 百分网手机站

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

时间:2020-09-25 19:00:12 C语言 我要投稿

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

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

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

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

  参数说明:

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

  写个范例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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 st.st_size;
}
 
int main(void)
{
    int fd = open("test.py",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>


【C语言用fstat函数获取文件的大小】相关文章:

有关C语言中获取文件状态的相关函数小结11-20

C语言文件操作函数11-04

C语言文件操作函数freopen详解11-20

C语言文件操作中fgets与fputs函数讲解10-22

C语言函数 atoi()10-28

浅谈C语言函数10-22

C语言函数的含义10-04

C语言函数的声明以及函数原型10-05

关于C语言对函数11-20