tags:

views:

612

answers:

6

I need to determin the byte size of a file.

The coding language is C++ and the code should work with Linux, windows and any other operating system. This implies using standard C or C++ functions/classes.

This trivial need has apparently no trivial solution.

+5  A: 

Using std's stream you can use:

std::ifstream ifile(....);
ifile.seekg(0, std::ios_base::end);//seek to end
//now get current position as length of file
ifile.tellg();

If you deal with write only file (std::ofstream), then methods some another:

ofile.seekp(0, std::ios_base::end);
ofile.tellp();
Dewfy
Open the file in binary or you might get the wrong result. Text ifstreams could do `\r\n` to `\n` translation for instance.
MSalters
The problem is that tellg() returns a value of type streampos. It is usually an int, but it can also be another type. Though I'll keep it as an answer.
chmike
My answer actually reflects that fact because my first iteration was off the top of my head until someone pointed out the mistake and marked me down for it.
graham.reeds
richb
-1: Opening file is bad idea. Moreover, you cannot check size of, for example, `/etc/shadow` this way.
el.pescado
A: 

Simples:

std::ifstream ifs; 
ifs.open("mybigfile.txt", std::ios::bin); 
ifs.seekg(0, std::ios::end); 
std::fpos pos = ifs.tellg();
graham.reeds
On 32-bit systems, size_t is 32 bits. So this fails with files of 4GB or larger.
user9876
I wrote this off the cuff with no reference. Looking at my code there are some problems which I have corrected.
graham.reeds
+3  A: 

If you only need the file size this is certainly overkill but in general I would go with Boost.Filesystem for platform-independent file operations. Amongst other attribute functions it contains

template <class Path> uintmax_t file_size(const Path& p);

You can find the reference here. Although Boost Libraries may seem huge I found it to often implement things very efficiently. You could also only extract the function you need but this might proof difficult as Boost is rather complex.

Sebastian
+2  A: 

You can use stat system call:

#ifdef WIN32 
_stat64()
#else
stat64()
Adil
It's worth noting that `stat` family of functions is part of POSIX, so they work on UNIX and UNIX-like systems as well.
el.pescado
A: 

Often we want to get things done in the most portable manner, but in certain situations, especially like this, I would strongly recommend using system API's for best performance.

the100rabh
+1  A: 

Portability requires you to use the least common denominators, which would be C. (not c++) The method that I use is the following.

#include <stdio.h>

long filesize(const char *filename)
{
FILE *f = fopen(filename,"rb");  /* open the file in read only */

long size = 0;
  if (fseek(f,0,SEEK_END)==0) /* seek was successful */
      size = ftell(f);
  fclose(f);
  return size;
}
iplayfast