2

Possible Duplicate:
Using C++ filestreams (fstream), how can you determine the size of a file?
file size in c program

I want to retrive the size of a file and for this I implemented in this way

(void)fseek(m_fp, 0, SEEK_END); // Set the file pointer to the end of the file
pFileSize = ftell(m_fp);        // Get the file size
(void)fseek(m_fp, oldFilePos, SEEK_SET);  // Put back the file pointer at the original location

This is not feasible for out need and is ther anyother way to get the file size or check whether the file contain and data

Community
  • 1
  • 1
Sijith
  • 3,122
  • 14
  • 52
  • 86

3 Answers3

6

You can use stat

#include <sys/types.h>
#include <sys/stat.h>
#if defined (_WIN32)
#  include <io.h> // make portable for windows
#else
#include <unistd.h>
#endif

struct stat st;
stat (filename, &st);
std::cout << st.st_size;
tozka
  • 2,751
  • 16
  • 20
  • 2
    Note that stat is not a part of C or C++ but POSIX. – P.P Oct 09 '12 at 07:07
  • fstat() or fstat64() are variations on stat() that use a FILE *. Given you already have m_fp in your code, I suggest you use fstat(). – Concrete Gannet Oct 09 '12 at 07:12
  • [fstat ()](http://linux.die.net/man/2/fstat) uses int file handle (returned by `open`) and not `FILE*` (from `fopen`) – tozka Oct 09 '12 at 07:18
0

If it is a binary stream, then pFileSize is the number of bytes from oldFilePos to the end of the file.

kuniqs
  • 198
  • 9
  • From the C standard: `A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.`, `Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream...` – Alexey Frunze Oct 09 '12 at 09:07
0

What you wrote is a 100% multiplatform way of doing what you need. Use your operating system's calls to do more, stat() on Unix-like OSes or GetFileAttributesEx() on Windows.

LubosD
  • 710
  • 5
  • 16
  • 1
    -1. No, it's not. From the C standard: `A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.`, `Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream...` – Alexey Frunze Oct 09 '12 at 09:06
  • Is there actually such a platform that doesn't support SEEK_END in stdio? – LubosD Oct 12 '12 at 11:50
  • I can't tell your for sure what platforms (compilers/stdlibs/OSes) don't support it, but I think I have been beaten by it once. – Alexey Frunze Oct 12 '12 at 11:54