方式一:
#include <stdio.h>
#include <sys/stat.h>
unsigned long get_file_size(const char *path)
{
unsigned long filesize = 0;
struct stat statbuff;
if(stat(path, &statbuff) < 0)
{
printf("get file(%s) property failed ", path);
return filesize;
}
else
{
filesize = statbuff.st_size;
}
return filesize;
}
int main(int argc,char **argv)
{
int i = 0;
unsigned long lLen = 0;
for(i = 1; i < argc; i++)
{
printf("argc = %d, argv=%s ",argc,argv[i]);
lLen = get_file_size(argv[i]);
printf("S_IFREG=%d,,0x%x, lLen=%lu ", S_IFREG, S_IFREG,lLen);
}
return 0;
}
#include <sys/stat.h>
unsigned long get_file_size(const char *path)
{
unsigned long filesize = 0;
struct stat statbuff;
if(stat(path, &statbuff) < 0)
{
printf("get file(%s) property failed ", path);
return filesize;
}
else
{
filesize = statbuff.st_size;
}
return filesize;
}
int main(int argc,char **argv)
{
int i = 0;
unsigned long lLen = 0;
for(i = 1; i < argc; i++)
{
printf("argc = %d, argv=%s ",argc,argv[i]);
lLen = get_file_size(argv[i]);
printf("S_IFREG=%d,,0x%x, lLen=%lu ", S_IFREG, S_IFREG,lLen);
}
return 0;
}
方法二:
unsigned long get_file_size_seek(const char *path)
{
unsigned long filesize = 0;
long curposition = -1;
FILE *fp = NULL;
fp = fopen(path, "r");
if(fp == NULL)
{
printf("fopen file(%s) failed ", path);
return filesize;
}
curposition = ftell(fp);
printf("curposition = %ld ",curposition);//curposition =0
if (0 != fseek(fp, 0L, SEEK_END))
{
printf("fseek failed ");
if (NULL != fp)
{
fclose(fp);
fp = NULL;
}
}
filesize = ftell(fp);
fclose(fp);
return filesize;
}
{
unsigned long filesize = 0;
long curposition = -1;
FILE *fp = NULL;
fp = fopen(path, "r");
if(fp == NULL)
{
printf("fopen file(%s) failed ", path);
return filesize;
}
curposition = ftell(fp);
printf("curposition = %ld ",curposition);//curposition =0
if (0 != fseek(fp, 0L, SEEK_END))
{
printf("fseek failed ");
if (NULL != fp)
{
fclose(fp);
fp = NULL;
}
}
filesize = ftell(fp);
fclose(fp);
return filesize;
}
ftell函数是用来获取文件的当前读写位置;
函数原型: long ftell(FILE *fp)
函数功能:获取流式文件的当前读写位置,
返回值:当前读写位置偏离文件头部的字节数.
fseek函数是 用来设定文件的当前读写位置.
函数原型: int fseek(FILE *fp,long offset,int origin);
函数功能:把fp的文件读写位置指针移到指定的位置.
fseek(fp,20,SEEK_SET); 意思是把fp文件读写位置指针从文件开始后移20个字节.