2014-04-04 58 views

回答

6

在大多數系統中,有stat()fstat()功能(不是ANSI-C的一部分,但POSIX的一部分)。對於Linux,請查看man page

編輯:對於Windows,文檔是here

編輯:對於一個更便攜版本,使用Boost庫:

#include <iostream> 
#include <boost/filesystem.hpp> 
using namespace boost::filesystem; 

int main(int argc, char* argv[]) 
{ 
    if (argc < 2) 
    { 
    std::cout << "Usage: tut1 path\n"; 
    return 1; 
    } 
    std::cout << argv[1] << " " << file_size(argv[1]) << '\n'; 
    return 0; 
} 
+0

函數['stat()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html)和 [''fstat()'](http://pubs.opengroup.org /onlinepubs/9699919799/functions/fstat.html)是POSIX的一部分。一個使用文件名,另一個使用打開的文件描述符。你是正確的,他們不是標準C的一部分。 –

3
#include <cstdio> 

FILE *fp = std::fopen("filename", "rb"); 
std::fseek(fp, 0, SEEK_END); 
long filesize = std::ftell(fp); 
std::fclose(fp); 

或者,使用ifstream

#include <fstream> 

std::ifstream fstrm("filename", ios_base::in | ios_base::binary); 
fstrm.seekg(0, ios_base::end); 
long filesize = fstrm.tellg(); 
+0

這很好地工作,除非你在32位長整型(​​32位Unix或Windows 32位或64位)的系統上,並且該文件是2 GiB或更大。那麼你有一個問題 - 你無法將所需的額外位精確地表示爲一個32位值。 –

0

這應該工作:

uintmax_t file_size(std::string path) { 
    return std::ifstream(path, std::ios::binary|std::ios::ate).tellg(); 
}