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

在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       else
12       {
13             fseek (pFile, 0, SEEK_END);   ///将文件指针移动文件结尾
14             size=ftell (pFile); ///求出当前文件指针距离文件开始的字节数
15             fclose (pFile);
16             printf ("Size of file.cpp: %ld bytes.
",size);
17       }
18       return 0;
19 }
原文地址:https://www.cnblogs.com/xudong-bupt/p/3506772.html