Publi

Tamaño de archivo para seres humanos (PHP,C++ y C)

Cuando obtenemos un tamaño de archivo, lo obtendremos en bytes, aunque está bien tener esa información en otras unidades, sobre todo, para expresar las cantidades al usuario de una forma más amigable.

1
2
3
4
5
6
7
8
9
function human_size ($tam) {
        $i = 0;
        $unids=array("bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb");
        while ($tam>1024) {
                $tam = $tam /1024;
                $i++;
        }
        return number_format($tam,2,",",".").$unids[$i];
}

Ahora sólo tenemos que llamar a human_size(filesize(‘archivo’)), por ejemplo, para dar el tamaño de un archivo.
En C++ podemos por ejemplo hacer lo siguiente:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <sstream>

using namespace std;

string human_size(long double size)
{
  static string units[10]={"bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb"};
  ostringstream out;
  int i= 0;

  while (size>1024) {
    size = size /1024;
    i++;
  }

  out.precision(3);
  out<<size<<units[i];
  return out.str();
}

int main()
{
  cout <<human_size(1232312333)<<endl;
}

Y ya puestos, lo hacemos en C de la siguiente forma:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

char *human_size(char *store, long double size)
{
  static char units[10][6]={"bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb"};  
  int i= 0;

  while (size>1024) {
    size = size /1024;
    i++;
  }

  sprintf(store,"%.2Lf%s",size, units[i]);

  return store;
}

int main()
{
  char cadena[30];
  printf("Size: %s\n", human_size(cadena, 1293323872));
}

Nota: Sé que he puesto muchas unidades: «bytes», «Kilobytes», «Megabytes», «GigaBytes», «Terabytes», «Petabytes», «Exabytes», «Zetabytes», «Yottabytes» y «Brontobytes», y que las variables no almacenarán valores tan grandes, pero bueno, por tener una referencia de las unidades en un lugar seguro 🙂

También podría interesarte....

There are 6 comments left Ir a comentario

  1. Pingback: Bitacoras.com /

  2. Pingback: Poesía binaria » Tamaño de un fichero en C /

  3. Pingback: Binary prose » File sizes for humans (PHP, C, C++) /

  4. Pingback: Cómo hacer una barra de progreso gráfica para las transferencias con rsync – Poesía Binaria /

  5. Pingback: Cómo obtener información de salud de tu sistema Linux o tu servidor en C y C++ (I. Memoria) – Poesía Binaria /

  6. 토토사이트 /
    Usando Google Chrome Google Chrome 124.0.0.0 en Windows Windows NT

    It’s a game. Five dollars is free. Try it It’s not an easy game ->-> 토토사이트.com

Leave a Reply