[cs631apue] humanize_number

Aubhik Mazumdar amazumda at stevens.edu
Tue Oct 9 23:59:18 EDT 2018


Has anyone used humanize_number in their ls assignment to convert the file
size to human readable format?

When I use it, I can't seem to get the precision correct (similar to ls).
Here is the relevant code-

 void

 print_bytes(off_t fileSize,struct opts_holder opts){

     char bytes[5];

     int64_t actual_size = (int64_t)fileSize;

     char * suffix = "";

     if(opts._h){

         if(humanize_number(bytes,5,actual_size,suffix,HN_AUTOSCALE,HN_NOSPACE
| HN_B)==-1){

             printf("%7ld ",fileSize);

         } else

             (void)printf("%5s ",bytes);

     } else {

         (void)printf("%7ld ",fileSize);

     }

 };
The output I get is-

localhost$ ./ls -alh

drwxr-xr-x  5 aubhikcr7  users  512B Oct  9 20:43 .

drwxr-xr-x  6 aubhikcr7  users  512B Sep 29 00:16 ..

drwxr-xr-x  7 aubhikcr7  users  512B Oct  6 01:52 .git

-rw-r--r--  1 root       users  143B Oct  6 22:20 Makefile

drwxr-xr-x  2 aubhikcr7  users  512B Oct  4 18:34 dd

-rwxr-xr-x  1 aubhikcr7  users   15K Oct  9 20:43 ls

-rw-r--r--  1 aubhikcr7  users    6K Oct  9 19:10 ls.c

-rw-------  1 aubhikcr7  users  174K Oct  9 20:07 ls.core

-rw-r--r--  1 aubhikcr7  users  319B Oct  5 18:56 ls.h

-rw-r--r--  1 aubhikcr7  users    8K Oct  9 19:10 ls.o

-rw-r--r--  1 aubhikcr7  users    3K Oct  9 20:43 print_function.c

-rw-r--r--  1 aubhikcr7  users  129B Oct  5 21:56 print_function.h

-rw-r--r--  1 aubhikcr7  users    5K Oct  9 20:43 print_function.o

drwxr-xr-x  3 aubhikcr7  users    1K Oct  9 19:38 testdir

localhost$ ls -alh

total 214K

drwxr-xr-x  5 aubhikcr7  users  512B Oct  9 20:43 .

drwxr-xr-x  6 aubhikcr7  users  512B Sep 29 00:16 ..

drwxr-xr-x  7 aubhikcr7  users  512B Oct  6 01:52 .git

-rw-r--r--  1 root       users  143B Oct  6 22:20 Makefile

drwxr-xr-x  2 aubhikcr7  users  512B Oct  4 18:34 dd

-rwxr-xr-x  1 aubhikcr7  users   15K Oct  9 20:43 ls

-rw-r--r--  1 aubhikcr7  users  5.8K Oct  9 19:10 ls.c

-rw-------  1 aubhikcr7  users  174K Oct  9 20:07 ls.core

-rw-r--r--  1 aubhikcr7  users  319B Oct  5 18:56 ls.h

-rw-r--r--  1 aubhikcr7  users  7.7K Oct  9 19:10 ls.o

-rw-r--r--  1 aubhikcr7  users  3.2K Oct  9 20:43 print_function.c

-rw-r--r--  1 aubhikcr7  users  129B Oct  5 21:56 print_function.h

-rw-r--r--  1 aubhikcr7  users  5.1K Oct  9 20:43 print_function.o
drwxr-xr-x  3 aubhikcr7  users  1.0K Oct  9 19:38 testdir

As you can see, the file size for ls.c is 6K in my program whereas the ls
command outputs 5.8K. Similarly for other files.

Any help would be appreciated.

Thanks,
Aubhik Mazumdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.stevens.edu/pipermail/cs631apue/attachments/20181009/ce21b6dd/attachment-0001.html>


More information about the cs631apue mailing list