zoukankan      html  css  js  c++  java
  • 如何用C语言获取文件的大小

    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;
    }
    





  • 相关阅读:
    HTML导航条的制作
    图片样式加hover特效
    用表格制作商品购买页面--(table)
    CSS-盒子模型
    一些常见css样式加选择器
    css的一些样式
    HTML基本代码
    element-ui的tab切换同步步骤条 字符串转数字 数字转字符串
    vuex相关知识笔记
    js: 数组方法(中级)
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835349.html
Copyright © 2011-2022 走看看