用C语言获取文件的大小示例分享


查了一下发现同C语言的文件操作函数便可以很容易的实现这样的功能。在自己实现的函数中使用到的函数就只有fseek和ftell。它们的说明如下:

fseek

语法:

#include <stdio.h> int fseek( FILE *stream, long offset, int origin );

函数fseek()为给出的流设置位置数据. origin的值应该是下列值其中之一(在stdio.h中定义):

名称 说明
SEEK_SET 从文件的开始处开始搜索
SEEK_CUR 从当前位置开始搜索
SEEK_END 从文件的结束处开始搜索
fseek()成功时返回0,失败时返回非零. 你可以使用fseek()移动超过一个文件,但是不能在开始处之前. 使用fseek()清除关联到流的EOF标记.

ftell

语法:

#include <stdio.h> long ftell( FILE *stream );

代码如下:ftell()函数返回stream(流)当前的文件位置,如果发生错误返回-1.

#include <sys/stat.h>  
#include <unistd.h>  
#include <stdio.h>  
/* 
  函数名:getFileSize(char * strFileName) 
  功能:获取指定文件的大小 
  参数: 
    strFileName (char *):文件名 
  返回值: 
    size (int):文件大小 
 */
int getFileSize(char * strFileName)
{
  FILE * fp = fopen(strFileName, "r");
  fseek(fp, 0L, SEEK_END);
  int size = ftell(fp);
  fclose(fp);
  return size;
}
/* 
  函数名:getFileSizeSystemCall(char * strFileName)  
  功能:获取指定文件的大小 
  参数: 
    strFileName (char *):文件名 
  返回值: 
    size (int):文件大小 
 */
int getFileSizeSystemCall(char * strFileName)
{
  struct stat temp;
  stat(strFileName, &temp);
  return temp.st_size;
}
int main()
{
  printf("size = %d/n", getFileSize("getFileSize.cpp"));
  printf("size = %d/n", getFileSizeSystemCall("getFileSize.cpp"));
  return 0;
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3