C++ 获取某文件的大小(字节数)(大文件读写,支持大于2GB文件)

来源:互联网 发布:c语言中文版 编辑:程序博客网 时间:2024/04/24 18:26

一个文件的大小可能大于1GB , 用 __int64 来表示其大小.

#include <stdlib.h>
#include <string.h>
#include<stdio.h>
#include "io.h"

__int64 filesize( char *   path )

{
       _finddatai64_t filefind;
        int   done=0,handle;
        __int64 fs =-1;
        if((handle=_findfirsti64(path ,&filefind))==-1) return -1;
       

        if   (!(_A_SUBDIR== (_A_SUBDIR & filefind.attrib)))
        {                
           fs = filefind.size ;
                  
        }
        _findclose(handle);
       return fs;

}
int main(void)
{       
        
         __int64 fs ;
        char * fname = "c:\\0-1.jpg" ;
        fs = filesize( fname );
        printf( "file : %s ", fname );
        if ( fs==-1)
            printf( " not foind \n");
        else
            printf( " filesize= %I64d bytes\n", fs );
        return 0;
}

--- 结果 --

file : c:\0-1.jpg filesize= 315341 bytes

本程序在 WinGW gcc,   VC6.0 下测试通过.

-------------------------------------------------------------------------------

以下是在 VC2008 下测试通过:

// test2008.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <stdlib.h>
#include <string.h>
#include<stdio.h>
#include "io.h"

__int64 filesize( char *   path )

{
       _finddatai64_t filefind;
        int   done=0,handle;
        __int64 fs =-1;
        if((handle=_findfirsti64(path ,&filefind))==-1) return -1;
       

        if   (!(_A_SUBDIR== (_A_SUBDIR & filefind.attrib)))
        {                
           fs = filefind.size ;
                  
        }
        _findclose(handle);
       return fs;

}


int _tmain(int argc, _TCHAR* argv[])
{
__int64 fs ;
        char * fname = "c:\\0-1.jpg" ;
        fs = filesize( fname );
        printf( "file : %s ", fname );
        if ( fs==-1)
            printf( " not foind \n");
        else
            printf( " filesize= %I64d bytes\n", fs );
   getchar();
return 0;
}

原创粉丝点击