Summary of how C and C ++ obtain the file size

Source: Internet
Author: User

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

1. Methods in MFC: (C ++)

Cfilestatus status;

Cfile: getstatus ("D: \ test.txt", status );

Long lsizeoffile;

Lsizeoffile = status. m_size;

The value of lsizeoffile is the size of the D: \ test.txt file.

2. Five methods for getting the file size from standard C

(Note: "_ file _" refers to the current file. You can change it to a target file in a valid path, such as "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;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.