Mailing List Archive

Support open source code!


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

Re: sprintf



>>>>> "Darren" == Darren Cook <darren@example.com> writes:

    Darren> So in my code I often use this kind of code to append
    Darren> strings.

    Darren> char *p=buf; p+=sprintf(p,"First line\n");
    Darren> p+=sprintf(p,"Second line\n"); //etc.

    Darren> But GCC 2.7.2 on a Sun has it defined (in stdio.h) as:

    Darren> extern char *sprintf _PARAMS((char *, const char *, ...));

Gomen, ne.

    Darren> Q1. Is the char* it is returning a pointer to the
    Darren> beginning of the buffer, or to the end of the buffer when
    Darren> it has finished?

The only conceivable reason for declaring sprintf that way is to make
code like

    strcat(partially_filled_buffer, sprintf(" Sun libc %s.", "sucks"));

possible.  Beginning.

    Darren> Q2. Is there a way I can get round this?

    Darren> My best idea so far is to replace all occurences in my
    Darren> code of sprintf with mysprintf, and then put this code
    Darren> into a header file: 

    Darren> #if GCC_ON_SUN
    Darren> int mysprintf(char *buf,const char *fmt,...){
[ code omitted ]
    Darren> #else
    Darren> #define mysprintf sprintf
    Darren> #endif

    Darren> Is there a way to do something similar without having to
    Darren> rename sprintf in my code?

What's wrong with

#if GCC_ON_SUN
#include <stdarg.h>
int replacement_for_broken_Sun_sprintf(char *buf,const char *fmt,...){
    va_list argptr;
    va_start(argptr,fmt);
    int sz=vsprintf(buf,fmt,argptr);
    va_end(argptr);
    return sz;
}
#define sprintf replacement_for_broken_Sun_sprintf
#endif

???  It looks dangerous, but you should get the results you want, as
long as you haven't done something really creative with the name
sprintf.

I'd put the replacement code in a "compatibility library," though,
which gets built only on the Sun platform, and the declaration of
replacement_for_broken_Sun_sprintf in "portability.h" or something
like that.

Steve

-- 
                           Stephen John Turnbull
University of Tsukuba                                        Yaseppochi-Gumi
Institute of Policy and Planning Sciences  http://turnbull.sk.tsukuba.ac.jp/
Tennodai 1-1-1, Tsukuba, 305 JAPAN                 turnbull@example.com
-----------------------------------------------------------------
a word from the sponsor will appear below
-----------------------------------------------------------------
The TLUG mailing list is proudly sponsored by TWICS - Japan's First
Public-Access Internet System.  Now offering 20,000 yen/year flat
rate Internet access with no time charges.  Full line of corporate
Internet and intranet products are available.   info@example.com
Tel: 03-3351-5977   Fax: 03-3353-6096


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links