C語言用fstat函數獲取文件的大小
來源:文萃谷 1.85W
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> |