其他分享
首页 > 其他分享> > 计算文件大小:lseek、ftell、stat

计算文件大小:lseek、ftell、stat

作者:互联网

计算文件大小:

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

#include <stdio.h>

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

//核心lseek
int FileSize_1(char *buf)
{
    int n = -1;
    int fd = open(buf, O_RDONLY);
    if(-1 == fd)
    {
        printf("open error");
        return -1;
    }
    //lseek函数的返回值就是距离文件首位多少字节
    n = lseek(fd, 0, SEEK_END);
    close(fd);
    return n;
}

//核心ftell
int FileSize_2(char *buf)
{
    int n = -1;
    FILE *fd = fopen(buf, "r");
    if(NULL == fd)
    {
        printf("fopen error");
        return -1;
    }
    //将指针指向文件末尾
    int ret = fseek(fd, 0, SEEK_END);
    if(0 != ret)
    {
        printf("fopen error");
        return -1;
    }
    //读取当前指针距离文件开头多少字节
    n = ftell(fd);
    fclose(fd);
    return n;
}

//核心stat
int FileSize_3(char *buf)
{
    int n = -1;
    struct stat str;
    stat(buf, &str);
    n = str.st_size;
    return n;
}


int main()
{
    int size = 0;
    size = FileSize_1("LF.jpg");
    printf("%d\n",size);
    size = FileSize_2("LF.jpg");
    printf("%d\n",size);
    size = FileSize_3("LF.jpg");
    printf("%d\n",size);
}

 

标签:文件大小,stat,return,int,ftell,fd,printf,include,size
来源: https://www.cnblogs.com/JinShanCheShen/p/16099335.html