C/C++语言获取文件大小

来源:互联网 发布:美国行业自律数据保护 编辑:程序博客网 时间:2024/06/10 02:27

在C语言中测试文件的大小,主要使用二个标准函数。

1.fseek 

  函数原型:int fseek ( FILE * stream, long int offset, int origin );

  参数说明:stream,文件流指针;offest,偏移量;orgin,原(始位置。其中orgin的可选值有SEEK_SET(文件开始)、SEEK_CUR(文件指针当前位置)、SEEK_END(文件结尾)。

  函数说明:对于二进制模式打开的流,新的流位置是origin + offset。

2.ftell

  函数原型:long int ftell ( FILE * stream );

   函数说明:返回流的位置。对于二进制流返回值为距离文件开始位置的字节数。

 

获取文件大小C程序(file.cpp):

复制代码
 1 #include <stdio.h> 2  3 int main () 4 { 5       FILE * pFile; 6       long size; 7  8       pFile = fopen ("file.cpp","rb"); 9       if (pFile==NULL)10             perror ("Error opening file");11       else12       {13             fseek (pFile, 0, SEEK_END);   ///将文件指针移动文件结尾14             size=ftell (pFile); ///求出当前文件指针距离文件开始的字节数15             fclose (pFile);16             printf ("Size of file.cpp: %ld bytes.\n",size);17       }18       return 0;19 }
复制代码
原创粉丝点击