Linux系统编程之查看文件大小的三种方法(lseek、fseek和stat函数)

Linux系统编程之查看文件大小的方法,以前发过两种方法,即使用lseek和stat函数。今天再补充一种方法,即使用fseek和ftell函数实现。

#include <sys/types.h>
#include <unistd.h>
 
off_t lseek(int fd, off_t offset, int whence);
#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
 
int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);

完整的实现代码如下:

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

int main(void)
{
    FILE *fp;
    int fd, ret;
    long result;
    struct stat st;

    /* No.1:	LSEEK */
    if((fd = open(__FILE__, O_RDONLY)) < 0)
    {
        perror("Open Error");
        exit(1);
    }

    if((result = (long)lseek(fd, 0, SEEK_END)) < 0)
    {
        perror("Lseek Error");
        exit(1);
    }

    printf("File size:\t%ld\tLSEEK\n", result);
    close(fd);

    /* No.2:	FSEEK */
    if((fp = fopen(__FILE__, "r")) == NULL)
    {
        perror("Fopen Error");
        exit(1);
    }

    if(fseek(fp, 0, SEEK_END) < 0)
    {
        perror("Fseek Error");
        exit(1);
    }

    result = (long)ftell(fp);

    printf("File size:\t%ld\tFSEEK\n", result);
    fclose(fp);

    /* No.3:	STAT */
    if((ret = stat(__FILE__, &st)) < 0)
    {
        perror("Stat Error");
        exit(1);
    }

    result = (long)st.st_size;

    printf("File size:\t%ld\tSTAT\n", result);

    exit(0);
}

Leave a Reply

Your email address will not be published. Required fields are marked *