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

如题所述

intfile_size(char*filename)

{

FILE*fp=fopen(filename,"r");

if(!fp)return-1;

fseek(fp,0L,SEEK_END);

intsize=ftell(fp);

fclose(fp);

returnsize;

}

扩展资料

C语言获取文件长度及全部内容

FILE*fp;

fp=fopen("localfile","rb");//localfile文件名

fseek(fp,0L,SEEK_END);/*定位到文件末尾*/

flen=ftell(fp);/*得到文件大小*/

p=(char*)malloc(flen+1);/*根据文件大小动态分配内存空间*/

if(p==NULL)

{

fclose(fp);

return0;

}

fseek(fp,0L,SEEK_SET);/*定位到文件开头*/

fread(p,flen,1,fp);/*一次性读取全部文件内容*/

p[flen]=0;/*字符串结束标志*/

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-09-04

这与系统有关,不同的系统会提供不同的API函数,下面提供一种与系统无关的方法:


FILE *fp=fopen("C:\\Windows\\explorer.exe","rb");//打开文件
int size=0;
fseek(fp,0,SEEK_END);//将文件位置指针置于文件结尾
size=ftell(fp);//得到当前位置与文件开始位置的字节偏移量。
fclose(fp);
printf("%d",size/1024);//输出结果。

第2个回答  推荐于2017-09-18

两种方法:

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;
}

本回答被提问者和网友采纳
相似回答