• C和C++获取文件大小的方法总结


    出处:http://hi.baidu.com/kofeffect/blog/item/cd040c2b2979d8fee6cd40c4.html

    1.MFC中的方法:(C++)

    CFileStatus status;
    CFile::GetStatus("D:\\test.txt",status);
    long lSizeOfFile;
    lSizeOfFile = status.m_size;

    lSizeOfFile的值就是D:\\test.txt文件的大小

    2.标准C获得文件大小的5种方法
    (注意:"__FILE__"指的是当前文件,你可以改为有效路径的目标文件,比如"D:\\test.txt")
    #include "stdafx.h"
    #include "stdio.h"
    #include <sys/stat.h>
    #include <io.h>
    #include <FCNTL.H>


    int getfilesize()
    {
        int iresult;
        struct _stat buf;
        iresult = _stat(__FILE__,&buf);
        if(iresult == 0)
        {
            return buf.st_size;
        }
        return NULL;
    }

    int getfilesize01()
    {
        int fp;
        fp=_open(__FILE__,_O_RDONLY);
        if(fp==-1) 
            return NULL;
        return _filelength(fp);
        //return NULL;
    }

    int getfilesize02()
    {
        int fp;
        fp=_open(__FILE__,_O_RDONLY);
        if(fp==-1) 
            return NULL;
        return _lseek(fp,0,SEEK_END);
        //return NULL;
    }

    int getfilesize03()
    {
        int fp;
        fp=_open(__FILE__,_O_RDONLY);
        if(fp==-1) 
            return NULL;
        return _lseek(fp,0,SEEK_END);
        //return NULL;
    }

    int getfilesize04()
    {
        FILE *fp;
        if((fp=fopen(__FILE__,"r"))==NULL)
            return 0;
        fseek(fp,0,SEEK_END);
        return ftell(fp);    //return NULL;
    }

    int getfilesize05()
    {
        FILE *fp;
        char str[1];
        if((fp=fopen(__FILE__,"rb"))==NULL)
            return 0;
        for(int i = 0;!feof(fp);i++)
        {
            fread(&str,1,1,fp);
            
        }
        return i - 1;    //return NULL;
    }

    int main(int argc, char* argv[])
    {
        
        printf("getfilesize()=%d\n",getfilesize());
        printf("getfilesize01()=%d\n",getfilesize01());
        printf("getfilesize02()=%d\n",getfilesize02());
        printf("getfilesize03()=%d\n",getfilesize03());
        printf("getfilesize04()=%d\n",getfilesize04());
        printf("getfilesize05()=%d\n",getfilesize05());
        return 0;
    }

    作者:wqvbjhc
    出处:https://www.cnblogs.com/wqvbjhc/
    版权:本文版权归作者和博客园共有
    转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
  • 相关阅读:
    PAT 1135 Is It A Red-Black Tree
    PAT 1136 A Delayed Palindrome
    PAT 1135 Is It A Red-Black Tree
    PAT 1134 Vertex Cover
    PAT 1133 Splitting A Linked List
    PAT 1132 Cut Integer
    PAT 1131 Subway Map
    PAT 1130 Infix Expression
    dom4j解析xml
    type="file" 选择图片后预览
  • 原文地址:https://www.cnblogs.com/wqvbjhc/p/2465089.html
Copyright © 2020-2023  润新知