2010-03-09 13 views

Respuesta

75

Puede abrir el archivo con la bandera ios::ate (y ios::binary bandera), por lo que la tellg() función le dará directamente el tamaño del archivo:

ifstream file("example.txt", ios::binary | ios::ate); 
return file.tellg(); 
+4

@Dominik Honnef: en VS 2013 Update5 64 bit este enfoque, con _ios: ate_ y sin _seekg (0, ios: end) _ podría no funcionar para archivos de gran tamaño. Consulte http://stackoverflow.com/questions/32057750/how-to-get-the-filesize-for-large-files-in-c para obtener más información. –

+2

Esto no parece un buen enfoque. [tellg no informa el tamaño del archivo, ni el desplazamiento desde el principio en bytes] (http://stackoverflow.com/a/22986486/1835769). – displayName

+0

@displayName [cplusplus.com] (http://www.cplusplus.com/reference/istream/istream/seekg/) no está de acuerdo con esa afirmación: de hecho usa 'tellg()' para detectar tamaño de archivo. –

49

Usted puede buscar hasta el final, y luego calcular la diferencia:

std::streampos fileSize(const char* filePath){ 

    std::streampos fsize = 0; 
    std::ifstream file(filePath, std::ios::binary); 

    fsize = file.tellg(); 
    file.seekg(0, std::ios::end); 
    fsize = file.tellg() - fsize; 
    file.close(); 

    return fsize; 
} 
+0

increíble! thanks =) – warren

+0

ha cambiado size_t to streampos. – AraK

+7

Fuera de interés, ¿no se garantiza que la primera llamada a 'tellg' devolverá 0? –

8

De esta manera:

long begin, end; 
ifstream myfile ("example.txt"); 
begin = myfile.tellg(); 
myfile.seekg (0, ios::end); 
end = myfile.tellg(); 
myfile.close(); 
cout << "size: " << (end-begin) << " bytes." << endl; 
+9

Es posible que desee utilizar el 'std :: streampos' más apropiado en lugar de' long', ya que este último puede no ser tan amplio como el anterior, y 'streampos' * es * más que un número entero. –

-2

soy un novato, pero esta es mi autodidacta forma de hacerlo:

ifstream input_file("example.txt", ios::in | ios::binary) 

streambuf* buf_ptr = input_file.rdbuf(); //pointer to the stream buffer 

input.get(); //extract one char from the stream, to activate the buffer 
input.unget(); //put the character back to undo the get() 

size_t file_size = buf_ptr->in_avail(); 
//a value of 0 will be returned if the stream was not activated, per line 3. 
+5

, todo lo que hace es determinar si hay un primer carácter. ¿Cómo ayuda eso? – warren

10

No utilice tellg para determinar el tamaño exacto del archivo. La longitud determinada por tellg será mayor que la cantidad de caracteres que se pueden leer del archivo.

De stackoverflow pregunta tellg() function give wrong size of file?tellg no informa el tamaño del archivo, ni el desplazamiento desde el principio en bytes. Informa un valor de token que luego puede usarse para buscar en el mismo lugar, y nada más. (Ni siquiera está garantizado que pueda convertir el tipo a un tipo integral). Para Windows (y la mayoría de los sistemas que no son Unix), en modo texto, no hay una asignación directa e inmediata entre lo que devuelve el informe y la cantidad de bytes que debe leer para llegar a esa posición.

Si es importante saber exactamente cuántos bytes puede leer, la única manera de hacerlo es leyendo. Usted debe ser capaz de hacer esto con algo como:

#include <fstream> 
#include <limits> 

ifstream file; 
file.open(name,std::ios::in|std::ios::binary); 
file.ignore(std::numeric_limits<std::streamsize>::max()); 
std::streamsize length = file.gcount(); 
file.clear(); // Since ignore will have set eof. 
file.seekg(0, std::ios_base::beg); 
Cuestiones relacionadas