最近在翻apue,看到函数lseek时想到之前一个面试题,如何计算文件的大小,现将部分实现整理如下:
方法一标准库函数实现:

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main(int argc,char *argv[])
{
    FILE *fp;
    if(argc < 2)
    {
        printf("Usage:%s <file>\n",argv[0]);
    }
    
    if((fp=fopen(argv[1],"r")) == NULL)
    {
        perror("fail to fopen ");
        return -1;
    }
    fseek(fp,0,SEEK_END);
    printf("The size of %s is %ld\n",argv[1],ftell(fp));
    fclose(fp);
    return 0;
}

方法二系统调用实现:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
    int fd;
    off_t len;
    if(argc < 2)
    {
        printf("Usage:%s <file>\n",argv[0]);
    }
    
    if(-1 == (fd=open(argv[1],O_RDONLY)))
    {
        perror("fail to fopen ");
        return -1;
    }
    len = lseek(fd,0,SEEK_END);
    printf("The size of %s is %lld\n",argv[1],len);
    close(fd);
    return 0;
}

方法三-stat lstat fstat等

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

int main(int argc,char *argv[])
{
    struct stat st;
    
    if(argc < 2)
    {
        printf("Usage:%s <file>\n",argv[0]);
    }

    if( -1 == stat(argv[1],&st))
    {
        return -1;
    }
    
    printf("The size of %s is %lld\n",argv[1],st.st_size);
    return 0;
}