Usando C ++ FileStreams (fstream), ¿cómo se puede determinar el tamaño de un archivo? [duplicar]

StackOverflow https://stackoverflow.com/questions/2409504

  •  18-09-2019
  •  | 
  •  

Pregunta

    

Esta pregunta ya tiene una respuesta aquí:

         

Estoy seguro de que simplemente he echado de menos esto en el manual, pero ¿cómo se determina el tamaño de un archivo (en bytes) usando la clase istream C ++ 's de la cabecera fstream?

¿Fue útil?

Solución

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

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

Otros consejos

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;
}

No utilice tellg para determinar el tamaño exacto del archivo. La longitud determinada por tellg será mayor que el número de caracteres se puede leer en el archivo.

A partir de la función cuestión stackoverflow tellg () dan tamaño incorrecto del archivo? tellg no informa del tamaño del archivo, ni el desplazamiento desde el principio en bytes. Se informa de un valor simbólico, que luego puede usarse para buscar el mismo lugar, y nada más. (No es ni siquiera garantiza que pueda convertir el tipo a un tipo entero.). Para Windows (y la mayoría de los sistemas no Unix), en el modo de texto, no hay ninguna asignación directa e inmediata entre lo tellg devoluciones y el número de bytes que debe leer para llegar a esa posición.

Si es importante saber exactamente cuántos bytes se puede leer, la única manera de hacerlo de forma fiable por lo que es mediante la lectura. 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 );

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;

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.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top