christopher diggins said:
Is there a simpler way to query the size of a file in C++ other than the
following:
unsigned int FileSize(const char* sFileName)
{
std::ifstream f;
f.open(sFileName);
if (!f.Good()) { return 0; }
std::ifstream:
os_type begin_pos = f.tellg();
f.seekg(0, std::ios_base::end);
return f.tellg() - begin_pos;
}
TIA
#include <iostream>
#include <iomanip>
#include <fstream>
#include <limits.h>
#include <assert.h>
using namespace std;
typedef unsigned long long ullong;
#define MAX_FILENAME_LEN 20
#define MAX_FILESIZE_LEN ((sizeof(ullong) * CHAR_BIT) - 2)
#define MAX_FILESIZE_VALUE (static_cast<ullong>(1) << (MAX_FILESIZE_LEN))
#define SETW_FILESIZE_LEN 15
// --------------------------------------
bool get_file_size(
const string& filename_i,
ullong& filesize_o
)
{
ifstream fin (filename_i.c_str());
if (fin.fail()) return false;
ullong start_pos, end_pos;
start_pos = fin.tellg();
fin.seekg(0, ios::end);
end_pos = fin.tellg();
filesize_o = end_pos - start_pos;
assert (filesize_o < MAX_FILESIZE_VALUE);
return true;
} // get_file_size
// --------------------------------------
void show_file_size(
const string& filename_i
)
{
ullong filesize;
cout << setw (MAX_FILENAME_LEN) << filename_i << " : ";
if (get_file_size (filename_i, filesize))
{
cout << setw (SETW_FILESIZE_LEN) << filesize << " bytes";
}
else
{
cout << "Unable to get file size";
}
cout << endl;
} // show_file_size
// --------------------------------------
int main (int argc, char** argv)
{
cout << "### Your input is : ";
for (int i = 0; i < argc; i++)
{
cout << argv
<< " ";
}
cout << endl;
cout << endl;
for (int i = 1; i < argc; i++)
{
show_file_size(argv);
}
return 0;
}