Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #160368 > unrolled thread

simple positional printf code review

Started byThiago Adams <thiago.adams@gmail.com>
First post2021-04-26 13:29 -0700
Last post2021-04-26 21:53 +0000
Articles 13 — 6 participants

Back to article view | Back to comp.lang.c


Contents

  simple positional printf code review Thiago Adams <thiago.adams@gmail.com> - 2021-04-26 13:29 -0700
    Re: simple positional printf code review Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2021-04-26 20:39 +0000
      Re: simple positional printf code review Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2021-04-26 20:49 +0000
        Re: simple positional printf code review Thiago Adams <thiago.adams@gmail.com> - 2021-04-26 14:00 -0700
          Re: simple positional printf code review Ben Bacarisse <ben.usenet@bsb.me.uk> - 2021-04-26 22:09 +0100
            Re: simple positional printf code review Thiago Adams <thiago.adams@gmail.com> - 2021-04-26 14:18 -0700
              Re: simple positional printf code review Ben Bacarisse <ben.usenet@bsb.me.uk> - 2021-04-27 01:46 +0100
                Re: simple positional printf code review "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2021-04-26 18:19 -0700
                  Re: simple positional printf code review Thiago Adams <thiago.adams@gmail.com> - 2021-04-27 04:44 -0700
          Re: simple positional printf code review Geoff <geoff@invalid.invalid> - 2021-04-26 17:58 -0700
            Re: simple positional printf code review Kaz Kylheku <563-365-8930@kylheku.com> - 2021-04-27 15:58 +0000
      Re: simple positional printf code review Thiago Adams <thiago.adams@gmail.com> - 2021-04-26 13:53 -0700
    Re: simple positional printf code review Kaz Kylheku <563-365-8930@kylheku.com> - 2021-04-26 21:53 +0000

#160368 — simple positional printf code review

FromThiago Adams <thiago.adams@gmail.com>
Date2021-04-26 13:29 -0700
Subjectsimple positional printf code review
Message-ID<6e8017a1-ca34-4e99-b541-b2ba87b9cc66n@googlegroups.com>
I need a function similar of snprint where  I can specify
the index of the argument in any order and reuse the 
same argument.

int format(char* s, size_t n, const char* format, ...);

char buffer[10];
format(buffer, sizeof buffer, "A %1 B %2 C %1", "ONE", "TWO");
this should format "A ONE B TWO C ONE"

this is what I have so far.

int format(char* s, size_t n, const char* format, ...)
{
    const char* arg[9] = { 0 };

    va_list args;
    va_start(args, format);
    const char* p = format;    
    while (*p)
    {
        if (*p == '%' && (*(p + 1) != '%'))
        {
            p++;
            int index = (*p - '0');
            if (arg[index] == NULL)
            {
                arg[index] = va_arg(args, char*);
                printf("SET %d = %s\n", index, arg[index]);
            }
        }
        p++;
    }
    va_end(args);


    p = format;
    int count = 0;
    for (;;)
    {
        if (*p == '%' && (*(p + 1) != '%'))
        {
            p++; //skip %
            int index = (*p - '0');
            const char * from = arg[index];
            while (*from)
            {
                if (count < n - 1)
                {
                    s[count] = *from;
                }
                count++;
                from++;
            }
            p++;
        }
        else
        {
            if (count < n - 1)
            {
                s[count] = *p;
            }
            count++;
            p++;
        }
    }
    

    s[count] = 0;

    return count;
}

Windows has this one

https://docs.microsoft.com/pt-br/cpp/c-runtime-library/printf-p-positional-parameters?view=msvc-160

but I am not sure if we can find the same function one linux
and them I decided to implement it.

[toc] | [next] | [standalone]


#160370

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2021-04-26 20:39 +0000
Message-ID<s678d7$8uf$1@dont-email.me>
In reply to#160368
On Mon, 26 Apr 2021 13:29:30 -0700, Thiago Adams wrote:

> I need a function similar of snprint where  I can specify
> the index of the argument in any order and reuse the 
> same argument.
[snip]
> but I am not sure if we can find the same function one linux
> and them I decided to implement it.

The Linux glibc implementation of the printf() family of functions recognizes
the %?$ modifier (as in "%3?s"), for specification of /which/ argument to use
to satisfy the formatting; "%3?s" would specify that this specific "%s" format
string will use the third argument, rather than the next argument.

So, in place of your  
  "A %1 B %2 C %1"
format list, you would specify
  "A %1?s B %2?s C %1?s"


PRINTF(3)                  Linux Programmer's Manual                 PRINTF(3)

NAME
       printf,   fprintf,   dprintf,  sprintf,  snprintf,  vprintf,  vfprintf,
       vdprintf, vsprintf, vsnprintf - formatted output conversion

...
   Format of the format string
   ...
       The arguments must correspond properly (after type promotion) with  the
       conversion  specifier.  By default, the arguments are used in the order
       given, where each '*' (see Field width and Precision  below)  and  each
       conversion  specifier asks for the next argument (and it is an error if
       insufficiently many arguments are given).  One can also specify explic-
       itly  which  argument  is  taken,  at  each  place where an argument is
       required, by writing "%m$" instead of '%' and  "*m$"  instead  of  '*',
       where  the  decimal integer m denotes the position in the argument list
       of the desired argument, indexed starting from 1.  Thus,

           printf("%*d", width, num);

       and

           printf("%2$*1$d", width, num);

       are equivalent.






-- 
Lew Pitcher
"In Skills, We Trust"

[toc] | [prev] | [next] | [standalone]


#160373

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2021-04-26 20:49 +0000
Message-ID<s6790c$8uf$2@dont-email.me>
In reply to#160370
damn keyboard, switched the questionmark and dollarsign on me :-S

On Mon, 26 Apr 2021 20:39:03 +0000, Lew Pitcher wrote:

> On Mon, 26 Apr 2021 13:29:30 -0700, Thiago Adams wrote:
> 
>> I need a function similar of snprint where  I can specify
>> the index of the argument in any order and reuse the 
>> same argument.
> [snip]
>> but I am not sure if we can find the same function one linux
>> and them I decided to implement it.
> 
> The Linux glibc implementation of the printf() family of functions recognizes
> the %?$ modifier (as in "%3?s")
                    as in "%3$s"
, for specification of /which/ argument to use
> to satisfy the formatting; "%3?s" 
                             "%3$s"

> would specify that this specific "%s" format
> string will use the third argument, rather than the next argument.
> 
> So, in place of your  
>   "A %1 B %2 C %1"
> format list, you would specify


>   "A %1?s B %2?s C %1?s"

    "A %1$s B %2$s C %1$s"
 
> 
> PRINTF(3)                  Linux Programmer's Manual                 PRINTF(3)
> 
> NAME
>        printf,   fprintf,   dprintf,  sprintf,  snprintf,  vprintf,  vfprintf,
>        vdprintf, vsprintf, vsnprintf - formatted output conversion
> 
> ...
>    Format of the format string
>    ...
>        The arguments must correspond properly (after type promotion) with  the
>        conversion  specifier.  By default, the arguments are used in the order
>        given, where each '*' (see Field width and Precision  below)  and  each
>        conversion  specifier asks for the next argument (and it is an error if
>        insufficiently many arguments are given).  One can also specify explic-
>        itly  which  argument  is  taken,  at  each  place where an argument is
>        required, by writing "%m$" instead of '%' and  "*m$"  instead  of  '*',
>        where  the  decimal integer m denotes the position in the argument list
>        of the desired argument, indexed starting from 1.  Thus,
> 
>            printf("%*d", width, num);
> 
>        and
> 
>            printf("%2$*1$d", width, num);
> 
>        are equivalent.




-- 
Lew Pitcher
"In Skills, We Trust"

[toc] | [prev] | [next] | [standalone]


#160375

FromThiago Adams <thiago.adams@gmail.com>
Date2021-04-26 14:00 -0700
Message-ID<f024614a-ed9b-48d9-86e1-041a649f185fn@googlegroups.com>
In reply to#160373
On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote:
> damn keyboard, switched the questionmark and dollarsign on me :-S
[..]
> > printf("%2$*1$d", width, num); 

This worked at Windows..but snprintf apparently is not implemented on windows.

_printf_p("A %1$s B %2$s C %1$s", "ONE", "TWO");

[toc] | [prev] | [next] | [standalone]


#160377

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2021-04-26 22:09 +0100
Message-ID<871rawhhxu.fsf@bsb.me.uk>
In reply to#160375
Thiago Adams <thiago.adams@gmail.com> writes:

> On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote:
>> damn keyboard, switched the questionmark and dollarsign on me :-S
> [..]
>> > printf("%2$*1$d", width, num); 
>
> This worked at Windows..but snprintf apparently is not implemented on
> windows.

That may be due to MS pushing the snprintf_s version.  Have you tried
that?  (I can't -- no access to an MS C ompiler.)

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#160378

FromThiago Adams <thiago.adams@gmail.com>
Date2021-04-26 14:18 -0700
Message-ID<dedb025c-1fd8-4816-860a-c02c8e23a87en@googlegroups.com>
In reply to#160377
On Monday, April 26, 2021 at 6:09:12 PM UTC-3, Ben Bacarisse wrote:
> Thiago Adams <thiago...@gmail.com> writes: 
> 
> > On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote: 
> >> damn keyboard, switched the questionmark and dollarsign on me :-S 
> > [..] 
> >> > printf("%2$*1$d", width, num); 
> > 
> > This worked at Windows..but snprintf apparently is not implemented on 
> > windows.
> That may be due to MS pushing the snprintf_s version. Have you tried 
> that? (I can't -- no access to an MS C ompiler.) 

In linux the same printf works for positional arguments...
in windows we need to use another function called  printf_p 
in windows normal printf("%2$*1$d", width, num);  does not work.

here there is a list of some positional version implemented.

https://docs.microsoft.com/pt-br/cpp/c-runtime-library/printf-p-positional-parameters?view=msvc-160

there is no snprintf_p

I think I will use my version..

int format(char* s, size_t n, const char* format, ...)
{
    const char* arg[10] = { 0 };
    _Static_assert(sizeof(arg) / sizeof(arg[0]) == 10, "0-9");

    va_list args;
    va_start(args, format);
    const char* p = format;
    while (*p)
    {
        if (*p == '%' && (*(p + 1) != '%'))
        {
            p++;
            int index = (*p - '0');
            if (index >= 0 && index <= 9)
            {
                if (arg[index] == 0)
                {
                    arg[index] = va_arg(args, char*);
                    printf("SET %d = %s\n", index, arg[index]);
                }
            }

        }
        p++;
    }
    va_end(args);


    p = format;
    int count = 0;
    while (*p)
    {
        if (*p == '%')
        {
            p++; //skip %
            if (*p >= '0' && *p <= '9')
            {
                int index = (*p - '0');
                const char* from = arg[index];
                
                if (from == NULL)
                {
                    from = "???";
                }

                while (from && *from)
                {
                    if (count < n - 1)
                    {
                        s[count] = *from;
                    }
                    count++;
                    from++;
                }
                p++;
            }
            else if (*p == '%')
            {
                if (count < n - 1)
                {
                    s[count] = *p;
                }
                count++;
                p++;
            }
            else
            {
                /*error?*/
            }
        }
        else
        {
            if (count < n - 1)
            {
                s[count] = *p;
            }
            count++;
            p++;
        }
    }

    if (count < n)
    {
        s[count] = 0;
    }
    else
    {
        s[n - 1] = 0;
    }

    return count;

    /*
      char buffer[50];
    int n = format(buffer, sizeof buffer, "A %% %1", "ONE");
    assert(strcmp(buffer, "A % ONE") == 0);
    assert(n == 7);

    n = format(buffer, sizeof buffer, "A %0 B %1 C %0", "ONE", "TWO");
    assert(n == 17);
    assert(strcmp(buffer, "A ONE B TWO C ONE") == 0);


    char buffer3[3];
    n = format(buffer3, sizeof buffer3, "%0", "ABC");
    assert(n == 2);
    assert(strcmp(buffer, "AB") == 0);
    */
}

int main()
{
    printf("A %1$s B %2$s C %1$s", "ONE", "TWO");

    char buffer[50];
    int n = format(buffer, sizeof buffer, "A %% %1", "ONE");
    assert(strcmp(buffer, "A % ONE") == 0);
    assert(n == 7);

    n = format(buffer, sizeof buffer, "A %0 B %1 C %0", "ONE", "TWO");
    assert(n == 17);
    assert(strcmp(buffer, "A ONE B TWO C ONE") == 0);


    char buffer3[3];
    n = format(buffer3, sizeof buffer3, "%0", "ABC");
    assert(n == 3);
    assert(strcmp(buffer3, "AB") == 0);
}


[toc] | [prev] | [next] | [standalone]


#160389

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2021-04-27 01:46 +0100
Message-ID<87h7jsftap.fsf@bsb.me.uk>
In reply to#160378
Thiago Adams <thiago.adams@gmail.com> writes:

> On Monday, April 26, 2021 at 6:09:12 PM UTC-3, Ben Bacarisse wrote:
>> Thiago Adams <thiago...@gmail.com> writes: 
>> 
>> > On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote: 
>> >> damn keyboard, switched the questionmark and dollarsign on me :-S 
>> > [..] 
>> >> > printf("%2$*1$d", width, num); 
>> > 
>> > This worked at Windows..but snprintf apparently is not implemented on 
>> > windows.
>> That may be due to MS pushing the snprintf_s version. Have you tried 
>> that? (I can't -- no access to an MS C ompiler.) 
>
> In linux the same printf works for positional arguments...
> in windows we need to use another function called  printf_p 
> in windows normal printf("%2$*1$d", width, num);  does not work.

Sorry, we've got a bit lost.  I was only commenting on "snprintf
apparently is not implemented on windows".  I was not referring to
whether any of these functions implemented positional parameters.  I
seem to remember someone saying that a lot of C functions are now hidden
by default because MS want you to use the _s versions.

Sorry if this side point was not clear.  And double sorry if I am wrong
about it altogether -- it is second hand information.

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#160392

From"Chris M. Thomasson" <chris.m.thomasson.1@gmail.com>
Date2021-04-26 18:19 -0700
Message-ID<s67oq4$off$1@gioia.aioe.org>
In reply to#160389
On 4/26/2021 5:46 PM, Ben Bacarisse wrote:
> Thiago Adams <thiago.adams@gmail.com> writes:
> 
>> On Monday, April 26, 2021 at 6:09:12 PM UTC-3, Ben Bacarisse wrote:
>>> Thiago Adams <thiago...@gmail.com> writes:
>>>
>>>> On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote:
>>>>> damn keyboard, switched the questionmark and dollarsign on me :-S
>>>> [..]
>>>>>> printf("%2$*1$d", width, num);
>>>>
>>>> This worked at Windows..but snprintf apparently is not implemented on
>>>> windows.
>>> That may be due to MS pushing the snprintf_s version. Have you tried
>>> that? (I can't -- no access to an MS C ompiler.)
>>
>> In linux the same printf works for positional arguments...
>> in windows we need to use another function called  printf_p
>> in windows normal printf("%2$*1$d", width, num);  does not work.
> 
> Sorry, we've got a bit lost.  I was only commenting on "snprintf
> apparently is not implemented on windows".  I was not referring to
> whether any of these functions implemented positional parameters.  I
> seem to remember someone saying that a lot of C functions are now hidden
> by default because MS want you to use the _s versions.

They are there, but you get a compile error. You need to use 
_CRT_SECURE_NO_WARNINGS.

https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-3-c4996?view=msvc-160


> 
> Sorry if this side point was not clear.  And double sorry if I am wrong
> about it altogether -- it is second hand information.
> 

[toc] | [prev] | [next] | [standalone]


#160401

FromThiago Adams <thiago.adams@gmail.com>
Date2021-04-27 04:44 -0700
Message-ID<233a99fb-ec49-4177-b974-41e134901254n@googlegroups.com>
In reply to#160392
On Monday, April 26, 2021 at 10:19:18 PM UTC-3, Chris M. Thomasson wrote:
> On 4/26/2021 5:46 PM, Ben Bacarisse wrote: 
> > Thiago Adams <thiago...@gmail.com> writes: 
> > 
> >> On Monday, April 26, 2021 at 6:09:12 PM UTC-3, Ben Bacarisse wrote: 
> >>> Thiago Adams <thiago...@gmail.com> writes: 
> >>> 
> >>>> On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote: 
> >>>>> damn keyboard, switched the questionmark and dollarsign on me :-S 
> >>>> [..] 
> >>>>>> printf("%2$*1$d", width, num); 
> >>>> 
> >>>> This worked at Windows..but snprintf apparently is not implemented on 
> >>>> windows. 
> >>> That may be due to MS pushing the snprintf_s version. Have you tried 
> >>> that? (I can't -- no access to an MS C ompiler.) 
> >> 
> >> In linux the same printf works for positional arguments... 
> >> in windows we need to use another function called printf_p 
> >> in windows normal printf("%2$*1$d", width, num); does not work. 
> > 
> > Sorry, we've got a bit lost. I was only commenting on "snprintf 
> > apparently is not implemented on windows". I was not referring to 
> > whether any of these functions implemented positional parameters. I 
> > seem to remember someone saying that a lot of C functions are now hidden 
> > by default because MS want you to use the _s versions.
> They are there, but you get a compile error. You need to use 
> _CRT_SECURE_NO_WARNINGS. 
> 
> https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-3-c4996?view=msvc-160
> > 
> > Sorry if this side point was not clear. And double sorry if I am wrong 
> > about it altogether -- it is second hand information. 
> >

There is some misunderstanding here.

printf, snprintf etc are implemented on windows. (some warnings but they are there)

the difference, printf on windows does not work with positional arguments.

This sample prints :

A ONE B TWO C ONE
A ONE B TWO C ONE
on Linux.
 
#include <stdio.h>

int main(){
   printf("A %1$s B %2$s C %1$s\n", "ONE", "TWO");
   char buffer[100];
   snprintf(buffer, sizeof buffer, "A %1$s B %2$s C %1$s\n", "ONE", "TWO");
   printf("%s", buffer);
}

..and on windows it prints.

A $s B $s C $s
A $s B $s C $s

However, windows has _printf_p that works (not sure if 100%) as linux printf.

See 
https://docs.microsoft.com/en-us/cpp/c-runtime-library/printf-p-positional-parameters?view=msvc-160

There is no _snprintf_p on windows, but I found _sprintf_p (just now) that has the buffer size.

https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/sprintf-p-sprintf-p-l-swprintf-p-swprintf-p-l?view=msvc-160

So this is the sample that works on Windows:

int main() {
   _printf_p("A %1$s B %2$s C %1$s\n", "ONE", "TWO");
    char buffer100[100];
    _sprintf_p(buffer100, sizeof buffer100, "A %1$s B %2$s C %1$s\n", "ONE", "TWO");
    printf("%s", buffer100);
}

Considering that this positional printf is not part of C standard I still considering
to use a custom implementation.

[toc] | [prev] | [next] | [standalone]


#160391

FromGeoff <geoff@invalid.invalid>
Date2021-04-26 17:58 -0700
Message-ID<68oe8g5vs7o684u7t71t2jp4ctjqohvrha@4ax.com>
In reply to#160375
On Mon, 26 Apr 2021 14:00:07 -0700 (PDT), Thiago Adams
<thiago.adams@gmail.com> wrote:

>On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote:
>> damn keyboard, switched the questionmark and dollarsign on me :-S
>[..]
>> > printf("%2$*1$d", width, num); 
>
>This worked at Windows..but snprintf apparently is not implemented on windows.
>
>_printf_p("A %1$s B %2$s C %1$s", "ONE", "TWO");
>

snprintf is implemented on Windows.

https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/snprintf-snprintf-snprintf-l-snwprintf-snwprintf-l?view=msvc-160

Per the document:
Beginning with the UCRT in Visual Studio 2015 and Windows 10, snprintf
is no longer identical to _snprintf. The snprintf function behavior is
now C99 standard compliant.

[toc] | [prev] | [next] | [standalone]


#160404

FromKaz Kylheku <563-365-8930@kylheku.com>
Date2021-04-27 15:58 +0000
Message-ID<20210427085417.210@kylheku.com>
In reply to#160391
On 2021-04-27, Geoff <geoff@invalid.invalid> wrote:
> On Mon, 26 Apr 2021 14:00:07 -0700 (PDT), Thiago Adams
><thiago.adams@gmail.com> wrote:
>
>>On Monday, April 26, 2021 at 5:49:23 PM UTC-3, Lew Pitcher wrote:
>>> damn keyboard, switched the questionmark and dollarsign on me :-S
>>[..]
>>> > printf("%2$*1$d", width, num); 
>>
>>This worked at Windows..but snprintf apparently is not implemented on windows.
>>
>>_printf_p("A %1$s B %2$s C %1$s", "ONE", "TWO");
>>
>
> snprintf is implemented on Windows.

Windows has an undocumented library called MSVCRT.DLL that applications
are not supposed to use. If you reverse-engineer that from some versions
of Windows, you might might find a C99 snprintf.

> https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/snprintf-snprintf-snprintf-l-snwprintf-snwprintf-l?view=msvc-160
>
> Per the document:
> Beginning with the UCRT in Visual Studio 2015 and Windows 10, snprintf

Visual Studio 2015 is a tool which suports C development that is not a
part of Windows. It provides a redistributable run-time.

According to this sense of "on windows", Windows has had a working
snprintf before VS 2015, because of Cygwin: another tool that supports C
development on Windows, also with its own libraries.

-- 
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal

[toc] | [prev] | [next] | [standalone]


#160374

FromThiago Adams <thiago.adams@gmail.com>
Date2021-04-26 13:53 -0700
Message-ID<f4c0ed6f-0041-423d-bf3f-93228cc0224bn@googlegroups.com>
In reply to#160370
On Monday, April 26, 2021 at 5:39:11 PM UTC-3, Lew Pitcher wrote:
> On Mon, 26 Apr 2021 13:29:30 -0700, Thiago Adams wrote: 
> 
> > I need a function similar of snprint where I can specify 
> > the index of the argument in any order and reuse the 
> > same argument.
> [snip]
> > but I am not sure if we can find the same function one linux 
> > and them I decided to implement it.
> The Linux glibc implementation of the printf() family of functions recognizes 
> the %?$ modifier (as in "%3?s"), for specification of /which/ argument to use 
> to satisfy the formatting; "%3?s" would specify that this specific "%s" format 
> string will use the third argument, rather than the next argument. 
> 
> So, in place of your
> "A %1 B %2 C %1"
> format list, you would specify 
> "A %1?s B %2?s C %1?s" 

I compare against with windows  _printf_p

Windows

https://godbolt.org/z/63r9xWzK7

#include <stdio.h>

int main(void)
{
    _printf_p("A %1?s B %2?s C %1?s", "ONE", "TWO");    
}

even in linux no success...

meanwhile..my new version is


int format(char* s, size_t n, const char* format, ...)
{
    const char* arg[] = { "??", "??", "??", "??", "??", "??", "??", "??", "??", "??" };
    _Static_assert(sizeof(arg) / sizeof(arg[0]) == 10, "0-9");

    va_list args;
    va_start(args, format);
    const char* p = format;
    while (*p)
    {
        if (*p == '%' && (*(p + 1) != '%'))
        {
            p++;
            int index = (*p - '0');
            if (index >= 0 && index <= 9)
            {
                arg[index] = va_arg(args, char*);
                printf("SET %d = %s\n", index, arg[index]);
            }
            
        }
        p++;
    }
    va_end(args);


    p = format;
    int count = 0;
    while (*p)
    {
        if (*p == '%')
        {
            p++; //skip %
            if (*p >= '0' && *p <= '9')
            {
                int index = (*p - '0');
                const char* from = arg[index];
                while (from && *from)
                {
                    if (count < n - 1)
                    {
                        s[count] = *from;
                    }
                    count++;
                    from++;
                }
                p++;
            }
            else if (*p == '%')
            {
                if (count < n - 1)
                {
                    s[count] = *p;
                }
                count++;
                p++;
            }
            else
            {
                /*error?*/
            }
        }
        else
        {
            if (count < n - 1)
            {
                s[count] = *p;
            }
            count++;
            p++;
        }
    }

    if (count < n)
    {
        s[count] = 0;
    }
    else
    {
        s[n - 1] = 0;
    }

    return count;
}

int main()
{
    char buffer[50];
    format(buffer, sizeof buffer, "A %% %1", "ONE");
    format(buffer, sizeof buffer, "A %0 B %1 %0", "ONE", "TWO");
}


[toc] | [prev] | [next] | [standalone]


#160381

FromKaz Kylheku <563-365-8930@kylheku.com>
Date2021-04-26 21:53 +0000
Message-ID<20210426143450.508@kylheku.com>
In reply to#160368
On 2021-04-26, Thiago Adams <thiago.adams@gmail.com> wrote:
>
> I need a function similar of snprint where  I can specify
> the index of the argument in any order and reuse the 
> same argument.
>
> int format(char* s, size_t n, const char* format, ...);
>
> char buffer[10];
> format(buffer, sizeof buffer, "A %1 B %2 C %1", "ONE", "TWO");
> this should format "A ONE B TWO C ONE"
>
> this is what I have so far.
>
> int format(char* s, size_t n, const char* format, ...)
> {

I would do this:

  int formata(char *dst, size_t dstsz, const char *format,
              const char *args[], size_t nargs)
  {
    /* loop over format string, extracting from args[] array,
       checking %n values against nargs limit */
  }

  int format(char *dst, size_t dstsz, const char *format,
             const char * arg, ...)
  {
    /* wrapper around formata that extracts the required
       array from variadic arguments. */
  }

You can write separate test cases against these two functions,
and from time to time, the array one could be useful.

If you make the array null-terminated, so that args[nargs] == NULL,
you can pass the main functions argv/argc to it.

You could have a test driver program:

  int main(int argc, char **argv)
  {
     if (argc >= 2) {
       const char *fmt = argv[1];
       char buf[1024] = { 0 };
       formata(buf, sizeof buf, argv + 2, argc - 2);
       fputs(buf, stdout);
       return 0;
     }

     return EXIT_FAILURE:
  }

and test that from a script. E.g.

  [ "$(./format "%0-%1" foo bar)" == "foo-bar" ] || test_failed

If the code aborts for an out-of-bound argument reference, the
script can check for that also.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.c


csiph-web