title: File size computation benchmark: C two times slower than C++?
body: <p>Consider the following code with 3 different versions of file size computation. </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstdio&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  
  inline long long int filesize1(const std::string&amp; filename)
  {
      std::ifstream filestream(filename.c_str(), std::ios::binary);
      std::streampos first = 0;
      std::streampos last = 0;
      long long int size = -1;
      if (filestream.is_open()) {
          filestream.seekg(0, std::ios::beg);
          first = filestream.tellg();
          filestream.seekg(0, std::ios::end);
          last = filestream.tellg();
          if ((first != -1) &amp;&amp; (last != -1) &amp;&amp; (last-first &gt;= 0)) {
              size = last-first;
          }
          filestream.close();
      }
      return size;
  }
  
  inline long long int filesize2(const std::string&amp; filename)
  {
      std::ifstream filestream(filename.c_str(), std::ios::binary);
      return (filestream) ? (static_cast&lt;long long int&gt;(filestream.seekg(0, std::ios::end).tellg()-filestream.seekg(0, std::ios::beg).tellg())) : (-1LL);
  }
  
  inline long long int filesize3(const std::string&amp; filename)
  {
      std::FILE* file = std::fopen(filename.c_str(), "rb");
      long long int size = -1;
      if (file) {
          std::fseek(file, 0, SEEK_END);
          size = std::ftell(file);
          std::fclose(file);
      }
      return size;
  }
  
  int main(int argc, char* argv[])
  {
      unsigned int n = 0;
      switch (std::atoi(argv[1])) {
          case 1: for (int i = 0; i &lt; std::atoi(argv[3]); ++i) n += filesize1(argv[2]); break;
          case 2: for (int i = 0; i &lt; std::atoi(argv[3]); ++i) n += filesize2(argv[2]); break;
          case 3: for (int i = 0; i &lt; std::atoi(argv[3]); ++i) n += filesize3(argv[2]); break;
      }
      std::cout&lt;&lt;n&lt;&lt;std::endl;
      return 0;
  }
  </code></pre>
  
  <p>First question : do I have the guarantee in all cases to have the same result for the 3 different versions ?</p>
  
  <p>Second question : why the version 3 in C is approximately 2 times slower than the first two versions ?</p>