Linux系统编程之查看文件大小的方法(lseek、fseek、stat)三种方法:
#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);
}