bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: printf %n is not documented


From: felix
Subject: Re: printf %n is not documented
Date: Sat, 7 Jan 2023 15:00:58 +0100

My two cents:

Le Tue, Dec 27, 2022 at 03:44:29PM -0500, Chet Ramey a écrit :
> 
> So maybe the better thing to do is to list the set of valid format
> specifiers from the standard printf(3) set.
> 
I'm not a C programmer, so I didn't hear about `printf %n` before this thread.
Re-reading all `man {1,3,3pl,3avr,...} printf' present on my host, I'v finally
found one short explanation, abount %n in printf(3), but with a lot of other
informations useless, regarding memory size and other. For sample, I'd never
used `%ld`, `%lld` nor`%qd` ( where `%q` is now binded to another bashism...)
(And a bug/remark about security flaw regarding memory misallocation when
using a format script from non validated user input, but if some flaws still
exists under bash, things are very differents)

The first use of this i've imaginated, was for differentiating char length
with byte length:

For this my previous version was: https://stackoverflow.com/a/31009961/1765658

  strU8DiffLen0() { local _cLen=${#1} LC_ALL=C;return $((${#1}-_cLen));}

  for string in Généralités Language "Yin Yang ☯";do
      strU8DiffLen0 "$string";
      printf " - %-*s is %2d chars length, but uses %2d bytes\n" \
           $((14+$?)) "'$string'" ${#string} $((${#string}+$?));
  done
   - 'Généralités'  is 11 chars length, but uses 14 bytes
   - 'Language'     is  8 chars length, but uses  8 bytes
   - 'Yin Yang ☯'   is 10 chars length, but uses 12 bytes

My new version of this became:

   strU8DiffLen1() { local _bl;printf -v _ %s%n "$1" _bl;return $((_bl-${#1}));}

This version is near two time quicker!!

   time for i in {1..10000};do strU8DiffLen0 'Généralité';ret=$?;done
   real    0m0.260s
   user    0m0.252s
   sys     0m0.005s

   time for i in {1..10000};do strU8DiffLen1 'Généralité';ret=$?;done
   real    0m0.148s
   user    0m0.144s
   sys     0m0.000s

But I have to confess:

  printf -v _ %s%n "$string" targetVar

This syntax has someting counter-intuitive.

So yes I think personely that printf chapter in bash man page could be expanded.

Thanks for all, regards!

-- 
 Félix



reply via email to

[Prev in Thread] Current Thread [Next in Thread]