D
David Mathog
Is there some method for restricting the maximum number of
characters that will be emitted by a printf() function?
Where printf() here is generic and refers to sprintf, fprintf, etc.
Here's an example of where this would be used (partial code!)
double thevar;
char abuf[256];
int oc;
/* thevar is set by some code here */
oc = sprintf(abuf,"%f",thevar);
The problem with this code is that even though abuf can hold
256 characters on some platforms a double is even larger than that,
and this results in sprintf writing off the end of abuf and over
other variables. I'm not entirely sure that one can predict
at run time the maximum number of digits needed for a double
unless perhaps the C standard specifies this. Unlike integer
types (where sizeof() gives the relevant info) doubles
could conceivably have different fractions of the bits in the
exponent.
Yes, this is for fixed width usage and basically I'd
be quite happy with something similar to the old Fortran overflow
method, where a field that is too big is just filled with
a row of asterisks. Since that seems not to be implemented in C
the closest I've come is to allocate a largish array and look
at the oc value set by sprintf(), then write * instead of the
string containing the formatted variable if the desired field
width is exceeded.
Thanks,
David Mathog
(e-mail address removed)
characters that will be emitted by a printf() function?
Where printf() here is generic and refers to sprintf, fprintf, etc.
Here's an example of where this would be used (partial code!)
double thevar;
char abuf[256];
int oc;
/* thevar is set by some code here */
oc = sprintf(abuf,"%f",thevar);
The problem with this code is that even though abuf can hold
256 characters on some platforms a double is even larger than that,
and this results in sprintf writing off the end of abuf and over
other variables. I'm not entirely sure that one can predict
at run time the maximum number of digits needed for a double
unless perhaps the C standard specifies this. Unlike integer
types (where sizeof() gives the relevant info) doubles
could conceivably have different fractions of the bits in the
exponent.
Yes, this is for fixed width usage and basically I'd
be quite happy with something similar to the old Fortran overflow
method, where a field that is too big is just filled with
a row of asterisks. Since that seems not to be implemented in C
the closest I've come is to allocate a largish array and look
at the oc value set by sprintf(), then write * instead of the
string containing the formatted variable if the desired field
width is exceeded.
Thanks,
David Mathog
(e-mail address removed)