c语言如何通过文件属性获取文件大小

c语言如何通过文件属性获取文件大小,第1张

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 )

}

/* 解题思路: 以只读方式打开某一文件,然后将文件指针银尺团定位在文件结尾的位置,利用ftell函数返回指针的在文件中的相对位置即困笑可。

*/

#include "stdio.h"

main()

{ FILE *fp /*定义文件锋橘指针*/

long cnt /*定义变量cnt用来存储文件大小数据*/

fp=fopen("c:\\1.txt","r") /*此处请填写测试文件的地址,并以只读("r")方式打开文件*/

if( fp==NULL ) /*如果打开的文件不存在,则退出*/

{ exit(0)

printf("文件打开失败!")

}

fseek(fp,0L,SEEK_END) /*利用fseek函数将指针定位在文件结尾的位置*/

cnt=ftell(fp) /*利用ftell函数返回指针相对于文件开头的位置,以字节计算*/

printf("文件所占的字节数为%ld个\n",cnt) /*进行输出*/

}

#include <io.h>

#include <悄物fcnt1.h>

void main()

{

int fd,size

char * buff

if ((fd=open("w.dat",O_RDONLY))==-1) {

printf("茄迅cannot open file\n")

exit(1)

}

size=filelength(fd)

buff=(char *) malloc(size)

if (read(fd,buff,size)!=size) {

printf("read error!!")

}

}

这样就启纳液OK了,希望采纳我


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/12193836.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-21
下一篇2023-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存