如何用C语言获取文件的大小

Python016

如何用C语言获取文件的大小,第1张

两种方法:

1、用stat()函数来获取

int main(){ struct stat st stat( "file.txt", &st )printf(" file size = %d\n", st.st_size)return 0}2、用ftell()函数来获取

int main(){FILE *fp fp=fopen( "file.txt", "r") fseek(fp, 0L, SEEK_END ) printf(" file size = %d\n", ftell(fp) ) return 0}

c语言可以通过stat()函数获得文件属性,通过返回的文件属性,从中获取文件大小

#include

<sys/stat.h>

可见以下结构体和函数

struct

stat

{

_dev_t

st_dev

_ino_t

st_ino

unsigned

short

st_mode

short

st_nlink

short

st_uid

short

st_gid

_dev_t

st_rdev

_off_t

st_size

//文件大小

time_t

st_atime

time_t

st_mtime

time_t

st_ctime

}

stat(const

char

*,

struct

_stat

*)

//根据文件名得到文件属性

参考代码:

#include <sys/stat.h>

void main( )

{

struct stat buf

if ( stat( "test.txt", &buf ) <0 )

{

perror( "stat" )

return

}

printf("file size:%d\n", buf.st_size )

}