1

考虑以下具有 3 个不同版本的文件大小计算的代码。

#include <iostream>
#include <cstdio>
#include <string>
#include <fstream>

inline long long int filesize1(const std::string& 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) && (last != -1) && (last-first >= 0)) {
            size = last-first;
        }
        filestream.close();
    }
    return size;
}

inline long long int filesize2(const std::string& filename)
{
    std::ifstream filestream(filename.c_str(), std::ios::binary);
    return (filestream) ? (static_cast<long long int>(filestream.seekg(0, std::ios::end).tellg()-filestream.seekg(0, std::ios::beg).tellg())) : (-1LL);
}

inline long long int filesize3(const std::string& 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 < std::atoi(argv[3]); ++i) n += filesize1(argv[2]); break;
        case 2: for (int i = 0; i < std::atoi(argv[3]); ++i) n += filesize2(argv[2]); break;
        case 3: for (int i = 0; i < std::atoi(argv[3]); ++i) n += filesize3(argv[2]); break;
    }
    std::cout<<n<<std::endl;
    return 0;
}

第一个问题:我是否保证在所有情况下对 3 个不同版本都有相同的结果?

第二个问题:为什么 C 中的版本 3 比前两个版本慢大约 2 倍?

4

0 回答 0