C语言获取文件大小的简单方法

方法一:通过文件流

//fseek函数是用来设定文件的当前读写位置.
//函数原型: int fseek(FILE *fp,long offset,int origin);
//函数功能: 把fp的文件读写位置指针移到指定的位置.
//fseek(fp,20,SEEK_SET); 意思是把fp文件读写位置指针从文件开始后移20个字节.

//ftell函数是用来获取文件的当前读写位置;
//函数原型: long ftell(FILE *fp)
//函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
//ban=ftell(fp);  是获取fp指定的文件的当前读写位置,并将其值传给变量ban.

//fseek函数与ftell函数综合应用:
//分析:可以用fseek函数把位置指针移到文件尾,再用ftell函数获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.


#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    long int size;
    char *buff;

    //以二进制读文件方式打开文件
    if ((fp = fopen("C:\\Users\\z00591975\\Desktop\\role_file.txt", "rb")) == NULL) {
        printf("Cannot open file\n");
        exit(1);
    } else {
        // 把文件的位置指针移到文件尾
        fseek(fp, 0, SEEK_END);
        // 获取文件长度
        size = ftell(fp);
        printf("该文件的长度为 %1d 字节\n", size);
        fclose(fp);
    }

    return 0;
}

方法二:fstat

#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
    struct stat buf;
    int fd;
    fd = open("C:\\Users\\z00591975\\Desktop\\role_file.txt", O_RDONLY);
    fstat(fd, &buf);
    printf("file size %d\n", buf.st_size);

    return 0;
}

方法三:stat

#include <sys/stat.h>
#include <stdio.h>

int main()
{
    struct stat buf;
    stat("C:\\Users\\z00591975\\Desktop\\role_file.txt", &buf);
    printf("file size %d\n", buf.st_size);

    return 0;
}

Guess you like

Origin blog.csdn.net/zhangyuexiang123/article/details/120874244