
#include <lcio.h>
int snprintf(char *dest, size_t maxlen, const char *format,
var1, var2, ...);
snprintf function writes formatted output to the area addressed by
dest under control of the string addressed by format until either
all format conversion specifications have been satisfied, or maxlen
characters have been written. The snprintf function is equivalent to the
sprintf function, except that no more than maxlen characters are
written to the dest string.
If the maxlen limit is reached
maxlen
snprintf function returns a negative value whose magnitude is equal
to the value of maxlen.
In all other respects, snprintf behaves identically to sprintf.
The string pointed to by format is in the same form as that used by
fprintf. Refer to the fprintf function description for detailed
information concerning format conversions.
snprintf function returns an integer value that equals, in magnitude,
the number of characters written to the area addressed by dest. If
the value returned is negative, then either the maxlen character limit
was reached or some other error, such as an invalid format specification, has
occurred. The one exception to this is if an error occurs before any characters
are stored, snprintf returns INT_MIN (-2**31).
maxlen value is 0, no characters are written, and snprintf
returns 0. If the value is greater than INT_MAX, then snprintf behaves
identically to sprintf, in that no limit checking is done on the number of
characters written to the output area.
No warnings concerning length errors are produced by snprintf, and the
only indication that the output may have been truncated or is incomplete is a
negative return value.
snprintf function, when invoked with a limit greater than 512
characters, calls the malloc function to obtain a temporary spill buffer
equal in size to the limit specified. If insufficient storage is available,
snprintf attempts to process the format specifications with an internal
512-byte spill buffer. In this case, individual conversion specifiers that
produce more than 512 characters may fail, and snprintf processing can
terminate prematurely.
#include <stdlib.h>
#include <lcio.h>
#define BUFFER_SIZE 40
#define LIMIT (BUFFER_SIZE - sizeof("..."))
char *_style = "tso";
main()
{
char fname[80];
char inbuf[300];
char buffer[BUFFER_SIZE];
FILE *input;
int i;
int count;
puts("Enter the name of an input file.");
gets(fname);
input = fopen(fname, "r");
if (!input) {
puts("File could not be opened.");
exit(EXIT_FAILURE);
}
for (i = 0; i < 5; ++i) {
if (!fgets(inbuf, 300, input)) /* end of file */
break;
count = snprintf(buffer, LIMIT,
"Line %d of file is : %s", i, inbuf);
if (count == LIMIT) buffer [LIMIT] = '0';
/* Output fit exactly. */
else if (count == -LIMIT) /* output truncated */
strcpy(buffer+LIMIT, "...");
puts(buffer);
}
fclose(input);
exit(EXIT_SUCCESS);
}
sprintf, vsnprintf
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.