网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的范文:

 

标题 用C语言获取文件的大小示例
范文
    查了一下发现同C语言的文件操作函数便可以很容易的实现这样的功能。在自己实现的函数中使用到的函数就只有fseek和ftell。它们的说明如下:
    fseek
    语法:
    view sourceprint?1 #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.
    #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;
    }
随便看

 

在线学习网范文大全提供好词好句、学习总结、工作总结、演讲稿等写作素材及范文模板,是学习及工作的有利工具。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/17 18:29:20