The C language USES the fstat function to get the size method of a file

  • 2020-06-12 10:07:17
  • OfStack

Before to get the file size is always dead, open1 file, then lseek, read to get the file size, this efficiency is really low, there may be careless and error.

Once I stumbled upon a function to get the file size in Android's source code, in the following example. You can avoid these problems with the fstat function.

Reference: baidu http: / / baike baidu. com/link & # 63; url = wh6msZkLUlTCx8P6YzujB3YoHaLLVaO68sQIIPR6ICj1yXYJxHfTDvxFwzjJ4YlpZZ8IDsKhKyf9EaCHo4ARHa

Function prototype: int fstat(int fildes, struct stat *buf);

Parameter description:

fstat() Used to copy the file state referred to by parameter fildes to the structure referred to by parameter buf (struct stat).

Write an example:


#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
// Gets the size of the file  
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!\n");
 return -1 ;
 }
 size = get_file_size(fd) ;
 printf("size:%d byte --->%.2fK\n",size,(float)size/1024);
 return 0 ; 
}

conclusion


Related articles: