Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculating file size

Status
Not open for further replies.

croc

Technical User
Jan 8, 2002
12
0
0
GB
Hello

Can anyone tell me how I can calculate the size of a file in bytes please.

Thanks
 
Using CFile::GetFileStatus and passing a CFileStatus struct to it will return all the info you are looking for.

Matt
 
Hello
Is CFile part of IOSTREAM.h or do i need to include another header, and how do I pass a CFilestatus struct?
 
Oh... you posted in the microsoft forum so I assumed you were using Microsoft Visual C++. CFile & CFileStatus are part of the Microsoft foundation classes (MFC) You could also use

fseek with a FILE pointer and use SEEK_END to get to the end of the file. When there, you can use ftell with the file pointer to return a long which will be the file size or -1 if an error occured.

Matt
 
Sorry, i missed the second 1/2 of the quesiton. If you are using MFC you just do:

Code:
CFile f;
f.Open(filename,CFile::modeRead);
CFileStatus fs;
f.GetStatus(fs);
long fileSize = fs.m_size;
f.Close();

Matt
 
If you you are not using MFC,you can use this:

#include <iostream.h>
#include <windows.h>
void main()
{
WIN32_FIND_DATA file;
HANDLE hFile;
long bsize; // size of file in &quot;bytes&quot;
float kbsize;// size of file in &quot;kilobytes&quot;
if (( hFile = FindFirstFile( &quot;path_to_file&quot;,&file )) == INVALID_HANDLE_VALUE )
{
cout<<&quot;Invalid File Handle.&quot;<<endl;
exit(0);
}
bsize = file.nFileSizeLow;
kbsize = ( float )bsize/1024;
cout << file.cFileName <<&quot; &quot;<<bsize<<&quot; bytes &quot;<<kbsize<<&quot; kb&quot;<<endl;
}

you have to replace 'path_to_file' with your file path.
 
just a little modification,i have forgot to close the &quot;search handle&quot;.

#include <iostream.h>
#include <windows.h>
void main()
{
WIN32_FIND_DATA file;
HANDLE hFile;
long bsize; // size of file in &quot;bytes&quot;
float kbsize;// size of file in &quot;kilobytes&quot;
if (( hFile = FindFirstFile( &quot;path_to_file&quot;,&file ))
== INVALID_HANDLE_VALUE )
{
cout<<&quot;Invalid File Handle.&quot;<<endl;
exit(0);
}
bsize = file.nFileSizeLow;
kbsize = ( float )bsize/1024;
cout << file.cFileName <<&quot; &quot;<<bsize<<&quot; bytes &quot;<<kbsize<<&quot; kb&quot;<<endl;
FindClose( hFile ); // close the search handle
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top