473,699 Members | 2,302 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

looking for statefull snprintf

Hello

Here is my situation: I have a char buf[1024]; that is used as a buffer

for a log output. Normally, I do:

rc = snprintf( buf, sizeof(buf), some_format, some_args );

This makes the formatting my output and then I flush the buffer.
In 90% of cases this works well, exept the cases when the format or the

arguments require more then 1024 bytes of formatted input.
There is no easy way to re-run snprintf() form 'last' position.

Suppose that using of asprintf(), another buffer and other kinds of
malloc() is not an option. Suppose the buffer must be preprocessed
before it hits the actual io.

Is there any open/closed libraries that solve the problem? Are there
any discussions held on the subject? Please provide the references.

Thanks
--
Dima

Aug 17 '06 #1
20 1903
On 2006-08-17, dimka <di************ @gmail.comwrote :
Hello

Here is my situation: I have a char buf[1024]; that is used as a buffer

for a log output. Normally, I do:

rc = snprintf( buf, sizeof(buf), some_format, some_args );

This makes the formatting my output and then I flush the buffer.
In 90% of cases this works well, exept the cases when the format or the

arguments require more then 1024 bytes of formatted input.
There is no easy way to re-run snprintf() form 'last' position.

Suppose that using of asprintf(), another buffer and other kinds of
malloc() is not an option. Suppose the buffer must be preprocessed
before it hits the actual io.

Is there any open/closed libraries that solve the problem? Are there
any discussions held on the subject? Please provide the references.
I'm not sure about libraries, but you could check out the code for
Chuck Falconers ggets() code (Google), or some of the stuff in my
ioutils package (see my sig for link).

Chuck's code will give you some idea on how to read in "unlimited"
amounts of data, and mine has some minimal input parsing you might
want to check out.

--
Andrew Poelstra <http://www.wpsoftware. net/projects>
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?" -Anon.
Aug 17 '06 #2
"dimka" <di************ @gmail.comwrite s:
Here is my situation: I have a char buf[1024]; that is used as a buffer
for a log output. Normally, I do:

rc = snprintf( buf, sizeof(buf), some_format, some_args );

This makes the formatting my output and then I flush the buffer.
In 90% of cases this works well, exept the cases when the format or the
arguments require more then 1024 bytes of formatted input.
There is no easy way to re-run snprintf() form 'last' position.
The usual solution is allocate a bigger buffer and try again,
instead of trying to restart from the point where the first try
left off, which as you say is not well supported.

The snprintf function returns the size of the buffer you need
(although you need to add 1 to make room for a terminating null).
--
"...Almost makes you wonder why Heisenberg didn't include postinc/dec operators
in the uncertainty principle. Which of course makes the above equivalent to
Schrodinger's pointer..."
--Anthony McDonald
Aug 17 '06 #3

dimka wrote:
Hello

Here is my situation: I have a char buf[1024]; that is used as a buffer
memory is selling nowdays for about $60 a gigabyte. By my calculations
you're allocating
$0.006144 of memory for this buffer. If you're paid $5 an hour, and
it took you 2.5 minutes to type this message, you've wasted $0.208333
just typing in this message. For that money, you could have bought 30
times the memory you allocated.

Hows about you either:

(1) Bump up the memory buffer size. Assuming it's a local variable,
it's not going to tie up the memory for more than a few microseconds.

(2) Write the data directly to the file with printf(), then there's no
need for the temporary buffer.

(3) Estimate the amount of memory needed beforehand, then add a penny.

Aug 17 '06 #4
Ben Pfaff wrote:
"dimka" <di************ @gmail.comwrite s:
>Here is my situation: I have a char buf[1024]; that is used as a
buffer for a log output. Normally, I do:

rc = snprintf( buf, sizeof(buf), some_format, some_args );

This makes the formatting my output and then I flush the buffer.
In 90% of cases this works well, exept the cases when the format
or the arguments require more then 1024 bytes of formatted input.
There is no easy way to re-run snprintf() form 'last' position.

The usual solution is allocate a bigger buffer and try again,
instead of trying to restart from the point where the first try
left off, which as you say is not well supported.

The snprintf function returns the size of the buffer you need
(although you need to add 1 to make room for a terminating null).
>From N869:
7.19.6.5 The snprintf function

Synopsis

[#1]

#include <stdio.h>
int snprintf(char * restrict s, size_t n,
const char * restrict format, ...);

Description

[#2] The snprintf function is equivalent to fprintf, except
that the output is written into an array (specified by
argument s) rather than to a stream. If n is zero, nothing
is written, and s may be a null pointer. Otherwise, output
characters beyond the n-1st are discarded rather than being
written to the array, and a null character is written at the
end of the characters actually written into the array. If
copying takes place between objects that overlap, the
behavior is undefined.

Returns

[#3] The snprintf function returns the number of characters
that would have been written had n been sufficiently large,
not counting the terminating null character, or a negative
value if an encoding error occurred. Thus, the null-
terminated output has been completely written if and only if
the returned value is nonnegative and less than n.

Taking advantage of this you can pretest for buffer overflow:

templgh = snprintf(NULL, 0, format, whatever);
if (templgh + bufindex >= sizeof(buffer) {
flushbuf(buffer ); bufindex = 0;
}
bufindex += snprintf(buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);

--
"The power of the Executive to cast a man into prison without
formulating any charge known to the law, and particularly to
deny him the judgement of his peers, is in the highest degree
odious and is the foundation of all totalitarian government
whether Nazi or Communist." -- W. Churchill, Nov 21, 1943
Aug 17 '06 #5
CBFalconer <cb********@yah oo.comwrites:
Ben Pfaff wrote:
>The usual solution is allocate a bigger buffer and try again,
instead of trying to restart from the point where the first try
left off, which as you say is not well supported.

The snprintf function returns the size of the buffer you need
(although you need to add 1 to make room for a terminating null).
[...]
Taking advantage of this you can pretest for buffer overflow:

templgh = snprintf(NULL, 0, format, whatever);
if (templgh + bufindex >= sizeof(buffer) {
flushbuf(buffer ); bufindex = 0;
}
bufindex += snprintf(buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);
You sure, but it's likely to be faster to call snprintf just once
in the common case (and occasionally a second time), instead of
always calling it twice.

Also, I would make the code above a little smarter, so that it
can expand the buffer in case flushing it isn't sufficient to
make enough room.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Aug 17 '06 #6
This is funny :) Everyone can cite the standard. But this is EXACTLY
the code that
does NOT work.
>
templgh = snprintf(NULL, 0, format, whatever);
if (templgh + bufindex >= sizeof(buffer) {
flushbuf(buffer ); bufindex = 0;
}
bufindex += snprintf(buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);
Aug 17 '06 #7
"dimka" <di************ @gmail.comwrite s:
>templgh = snprintf(NULL, 0, format, whatever);
if (templgh + bufindex >= sizeof(buffer) {
flushbuf(buffer ); bufindex = 0;
}
bufindex += snprintf(buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);

This is funny :) Everyone can cite the standard. But this is EXACTLY
the code that
does NOT work.
Perhaps you are using a pre-standard implementation of snprintf.
Some of these implementations just returned -1 when the string
wouldn't fit in the buffer. Then the caller is left to guess how
much room is needed and try again.
--
Peter Seebach on C99:
"[F]or the most part, features were added, not removed. This sounds
great until you try to carry a full-sized printout of the standard
around for a day."
Aug 17 '06 #8
Well, let me explain the problem again.
Lets assume that the buffer is empty, thus no need to flush it.
then

rc = snprintf( buffer, sizeof(buffer)-1, "%s", str );

Works pretty well. No buffer overrun, in the new standard
rc == strlen(str), in old standard rc == -1, thus I have a way
to check that there was the potential overrun.

The problem arises when strlen(str) sizeof(buffer).
In this situation the buffer will contain trunkated version
of str, I have the information that the string was
trunkated, but no way to say "hey, I have flushed the
buffer, please continue from the place where you
stopped". There must to be an alternative implementation
of snprintf() to do exactly what I want.
Ben Pfaff wrote:
"dimka" <di************ @gmail.comwrite s:
templgh = snprintf(NULL, 0, format, whatever);
if (templgh + bufindex >= sizeof(buffer) {
flushbuf(buffer ); bufindex = 0;
}
bufindex += snprintf(buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);
This is funny :) Everyone can cite the standard. But this is EXACTLY
the code that
does NOT work.

Perhaps you are using a pre-standard implementation of snprintf.
Some of these implementations just returned -1 when the string
wouldn't fit in the buffer. Then the caller is left to guess how
much room is needed and try again.
--
Peter Seebach on C99:
"[F]or the most part, features were added, not removed. This sounds
great until you try to carry a full-sized printout of the standard
around for a day."
Aug 17 '06 #9
dimka wrote:
This is funny :)

Please read the information below.
Brian
--
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or:
<http://www.caliburn.nl/topposting.html >
Aug 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2757
by: MaxMax | last post by:
Now... I have a problem... It's an engineering problem. I have a function, we will call it MyBigFunc. It's a function that can be easily built as a static method, because it is the only function that the "user" will use and it is stateless. So I wrote something like: class MyClass { public: static int MyBigFunc() { return 0;}
2
5414
by: ajm | last post by:
Hi, I'm refactoring some HTTP client code I wrote a while back and in the process I'm tightening up some of my string processing code (most of which involves parsing, replacing, concatenating strings etc.). I'm reading that it is better to use str functions like "snprintf" and to avoid using "strcat" altogether since the former more explicit protection against buffer overflow etc. Is this sort of comment good advice ?
2
1642
by: Bruno van Dooren | last post by:
Hi, this might be a strange question, but why is snprintf not guaranteed to nul terminate a string? i thought the whole point of those sn functions was to prevent these errors. sure, they prevent buffer overwrites, but callers can still screw up bad if they don't always make sure for themselves that the 0 is there before they let someone else read the contents.
2
3731
by: A. Farber | last post by:
Hello, I'm programming a web application and for that I'm trying to extend the standard C string functions, so that they can handle the application/x-www-form-urlencoded format (which encodes non-alphanumeric characters as %XY). I've written my own xstrlen(), xstrlcat(), xstrlcpy and xstrdup() (please see the source code on the bottom of this post).
14
13550
by: matevzb | last post by:
The C99 standard describes snprintf() in an awkward way, so it's hard (for me) to assume what the result will be in some situations. 1. The "Description" section states: "... Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array." 2. The "Returns" section states: "The snprintf function returns the...
0
801
by: ymsfa | last post by:
hello I would like to know how to access a statefull java web service from c#, I created a c# client but it dosen't maintain a statefull session and I found another method created by VS ( getInstAsync() ) however my web service method is getInst() why VS created another method ending with (Async)? so, my question is how to access a statefull java web service from c# application? thanks
11
44821
by: manjuks | last post by:
Hi All, I wants to know what is the difference between sprintf and snprintf? Thanks, Manjunath
0
8618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8916
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8885
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7752
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6534
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3058
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2348
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.