fsize.cpp

(plain text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**********************************************************************
 * How to get the size of a file in C/C++
 *
 * Successfully compiles and runs under (at least) the following:
 * - g++ 2.95.4 and 3.2 on Debian (Linux) and Cygwin
 * - Visual C++ 6.0 and .NET on Windows 2000
 * Should work on other platforms with minimal alteration
 * 
 * Note: The POSIX way is fastest because it merely inspects the file
 *       system, but may not work in all C/C++ environments. For this
 *       reason, C/C++ versions are provided for comparison.
 **********************************************************************/

/* C */
 
#include <stdio.h>

long fsize_c (const char *filename) {
  long result = -1;
  FILE *p;

  if ( (p = fopen(filename, "rb")) ) {
    fseek(p, 0, SEEK_END);
    result = ftell(p);
    fclose(p);
  }

  return result;
}

/**********************************************************************/

// C++

#include <fstream>

// ISO C++ returns istream::pos_type but g++ 2.95.4 does not;
// easier to typedef the correct return type to streampos
// than the other way around

#if !defined(__GNUC__) || __GNUC__ > 2
typedef std::ifstream::pos_type streampos;
#endif

streampos fsize_cpp (const char *filename) {
  return std::ifstream(filename,
		       std::ifstream::in | std::ifstream::binary
		       ).seekg(0, std::ifstream::end).tellg();
}

/**********************************************************************/

/* POSIX */

#include <sys/types.h>
#include <sys/stat.h>

#ifdef WIN32
#  define stat _stat
#endif

off_t fsize_posix (const char *filename) {
  struct stat st;
  return (stat(filename, &st) != -1) ? st.st_size : -1;
}

/**********************************************************************/

// C++ test code

#include <iostream>
#include <iomanip>
#include <cerrno>
#include <cstring>
using namespace std;

int main (int argc, char *argv[]) {
  cout.setf(cout.left);

  for (int i = 1; i < argc; ++i) {
    long size;

    cout << argv[i] << ":\n";

    errno = 0;
    size = fsize_c(argv[i]);
    cout.width(25);
    if (errno) cout << strerror(errno); else cout << size;

    cout << " | ";

    errno = 0;
    size = fsize_cpp(argv[i]);
    cout.width(25);
    if (errno) cout << strerror(errno); else cout << size;

    cout << " | ";

    errno = 0;
    size = fsize_posix(argv[i]);
    cout.width(25);
    if (errno) cout << strerror(errno); else cout << size;

    cout << '\n';
  }

  return 0;
}