如何用C语言获取文件的大小


今天看项目的代码过程中发现在linux下获取一个指定文件大小(字节为单位)的代码。查了一下发现是使用系统调用stat来实现,而这引起了我的兴趣,我发现在window下貌似没有提供这样的系统调用(不包括MFC),那么如何使用C语言或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.

至于stat调用,请详见:

代码如下:

/* 
    FileName: getFileName.cpp 
    Author: ACb0y 
    Create Time: 2011年2月12日20:45:31 
    Last modify Time: 2011年2月12日20:47:21 
 */ 
#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;  

运行结果如下:

相关内容