您的位置:首页 > 编程语言 > C语言/C++

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

2017-03-25 00:00 253 查看
ITAT复赛的一个题,涉及文件操作,不会=。=

回学校学习了下:

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调用,请详见:http://www.360doc.com/content/11/0110/16/4559801_85509847.shtml

代码如下:

#include <sys/stat.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 = %dbyte\n", getFileSize("naxienian.mp3"));
printf("size = %dbyte\n", getFileSizeSystemCall("naxienian.mp3"));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: