How to get the size in bytes of a file in C++?
How to get the size in bytes of a file in C++?
Using the C++ Standard Library’s fstream object makes this rather easy. I tested this method on Windows 7 and FreeBSD 7.2.
Lets say I have a file called MyFile. How do I get the size of it?
#include
#include
using namespace std;
int main()
{
char * fileName = “MyFile”;
fstream file(fileName, ios::in);
file.seekg(0, ios::end);
int sizeInBytes = file.tellg();
cout << fileName << " is " << sizeInBytes << " bytes long." << endl;
}
[/sourcecode]
That is great. It is simple and it works.
Now you can actually make a usable application out. Let's change this to take a parameter, the parameter should be a file, and output the size of the file.
[sourcecode language="cpp"]
#include
#include
using namespace std;
int main(int argc, char **argv)
{
char * fileName = argv[1];
fstream file(fileName, ios::in);
file.seekg(0, ios::end);
int sizeInBytes = file.tellg();
cout << fileName << " is " << sizeInBytes << " bytes long." << endl;
}
[/sourcecode]
Now if you build this into an executable called filesize
, you can run filesize MyFile
.
Ok, so their is an idea in the unix world (which I agree with usually) that output should not be chatty, so lets change the output line to only output the size in bytes of the file. This will make it easier for you to use shell scripts to and parse the output.
cout << sizeInBytes << endl;
[/sourcecode]
Now lets make it a little more rebust and error proof.
[sourcecode language="cpp"]
#include
#include
#include
#include
using namespace std;
void syntax(char * thisFile);
const char * stripPath(char * inPath);
int main(int argc, char **argv)
{
// Take only one paramter.
// Since there is a default parameter you have to check for 2 not 1
if (argc == 2)
{
char * fileName = argv[1];
fstream file(fileName, ios::in);
if (file)
{
file.seekg(0, ios::end);
int sizeInBytes = file.tellg();
cout << sizeInBytes << endl;
}
else
{
cout << "File error. The file you entered could not be sized." << endl;
}
}
else
{
syntax(argv[0]);
exit(1);
}
return 0;
}
void syntax(char * thisFile)
{
cout << "Syntax: " << endl;
cout << " " << stripPath(thisFile) << " Filename" << endl;
cout << endl;
cout << " Filename\t" << "Any file path value such as, MyFile, c:\\myfile, /root/myfile." << endl;
cout << endl;
}
const char * stripPath(char * inPath)
{
string path = inPath;
string fileName = path.substr(path.rfind("\\") + 1);
char * retVal = new char[fileName.size() + 1];
strcpy(retVal, fileName.c_str());
return retVal;
}
[/sourcecode]
No there shouldn't be any program crashes when you input an incorrect filename, or a file that you don't have access to.
Sources:
http://www.cplusplus.com/reference/iostream/istream/read/