avr_stdio(3)
๐ avr_stdio(3) โ standard IO, but make it AVR ๐
โจ NAME โจ
avr_stdio โ that's the name, bestie. It's giving standard IO for avr-libc. ๐
โจ SYNOPSIS โจ
๐ง Macros ๐ง
#define stdin (__iob[0])
#define stdout (__iob[1])
#define stderr (__iob[2])
#define EOF (-1)
#define fdev_set_udata(stream, u) do { (stream)->udata = u; }
while(0)
#define fdev_get_udata(stream) ((stream)->udata)
#define fdev_setup_stream(stream, put, get, rwflag)
#define _FDEV_SETUP_READ __SRD
#define _FDEV_SETUP_WRITE __SWR
#define _FDEV_SETUP_RW (__SRD|__SWR)
#define _FDEV_ERR (-1)
#define _FDEV_EOF (-2)
#define FDEV_SETUP_STREAM(put, get, rwflag)
#define fdev_close()
#define putc(__c, __stream) fputc(__c, __stream)
#define putchar(__c) fputc(__c, stdout)
#define getc(__stream) fgetc(__stream)
#define getchar() fgetc(stdin)
๐ง Typedefs ๐ง
typedef struct __file FILE
๐ง Functions ๐ง
int fclose (FILE *__stream)
int vfprintf (FILE *__stream, const char *__fmt, va_list __ap)
int vfprintf_P (FILE *__stream, const char *__fmt, va_list __ap)
int fputc (int __c, FILE *__stream)
int printf (const char *__fmt,...)
int printf_P (const char *__fmt,...)
int vprintf (const char *__fmt, va_list __ap)
int sprintf (char *__s, const char *__fmt,...)
int sprintf_P (char *__s, const char *__fmt,...)
int snprintf (char *__s, size_t __n, const char *__fmt,...)
int snprintf_P (char *__s, size_t __n, const char *__fmt,...)
int vsprintf (char *__s, const char *__fmt, va_list ap)
int vsprintf_P (char *__s, const char *__fmt, va_list ap)
int vsnprintf (char *__s, size_t __n, const char *__fmt, va_list ap)
int vsnprintf_P (char *__s, size_t __n, const char *__fmt, va_list ap)
int fprintf (FILE *__stream, const char *__fmt,...)
int fprintf_P (FILE *__stream, const char *__fmt,...)
int fputs (const char *__str, FILE *__stream)
int fputs_P (const char *__str, FILE *__stream)
int puts (const char *__str)
int puts_P (const char *__str)
size_t fwrite (const void *__ptr, size_t __size, size_t __nmemb, FILE *__stream)
int fgetc (FILE *__stream)
int ungetc (int __c, FILE *__stream)
char * fgets (char *__str, int __size, FILE *__stream)
char * gets (char *__str)
size_t fread (void *__ptr, size_t __size, size_t __nmemb, FILE *__stream)
void clearerr (FILE *__stream)
int feof (FILE *__stream)
int ferror (FILE *__stream)
int vfscanf (FILE *__stream, const char *__fmt, va_list __ap)
int vfscanf_P (FILE *__stream, const char *__fmt, va_list __ap)
int fscanf (FILE *__stream, const char *__fmt,...)
int fscanf_P (FILE *__stream, const char *__fmt,...)
int scanf (const char *__fmt,...)
int scanf_P (const char *__fmt,...)
int vscanf (const char *__fmt, va_list __ap)
int sscanf (const char *__buf, const char *__fmt,...)
int sscanf_P (const char *__buf, const char *__fmt,...)
int fflush (FILE *stream)
FILE * fdevopen (int(*put)(char, FILE *), int(*get)(FILE *))
๐ DETAILED DESCRIPTION ๐
#include <stdio.h>
๐ Introduction to the Standard IO facilities ๐
Okay so bestie, this file declares the standard IO facilities that are implemented in avr-libc. Due to the nature of the underlying hardware, only a limited subset of standard IO is implemented. There is no actual file implementation available, so only device IO can be performed. Since there's no operating system, the application needs to provide enough details about their devices in order to make them usable by the standard IO facilities. ๐ฆ
Due to space constraints, some functionality has not been implemented at all (like some of the printf conversions that have been left out). Nevertheless, potential users of this implementation should be warned: the printf and scanf families of functions, although usually associated with presumably simple things like the famous 'Hello, world!' program, are actually fairly complex which causes their inclusion to eat up a fair amount of code space. Also, they are not fast due to the nature of interpreting the format string at run-time. Whenever possible, resorting to the (sometimes non-standard) predetermined conversion facilities that are offered by avr-libc will usually cost much less in terms of speed and code size. ๐
๐ Tunable options for code size vs. feature set ๐
In order to allow programmers a code size vs. functionality tradeoff, the function vfprintf() which is the heart of the printf family can be selected in different flavours using linker options. See the documentation of vfprintf() for a detailed description. The same applies to vfscanf() and the scanf family of functions. ๐ฅ
๐ Outline of the chosen API ๐
The standard streams stdin, stdout, and stderr are provided, but contrary to the C standard, since avr-libc has no knowledge about applicable devices, these streams are not already pre-initialized at application startup. Also, since there is no notion of 'file' whatsoever to avr-libc, there is no function fopen() that could be used to associate a stream to some device. (See note 1.) Instead, the function fdevopen() is provided to associate a stream to a device, where the device needs to provide a function to send a character, to receive a character, or both. There is no differentiation between 'text' and 'binary' streams inside avr-libc. Character \n is sent literally down to the device's put() function. If the device requires a carriage return (\r) character to be sent before the linefeed, its put() routine must implement this (see note 2). โจ
As an alternative method to fdevopen(), the macro fdev_setup_stream() might be used to setup a user-supplied FILE structure. ๐
It should be noted that the automatic conversion of a newline character into a carriage return - newline sequence breaks binary transfers. If binary transfers are desired, no automatic conversion should be performed, but instead any string that aims to issue a CR-LF sequence must use '\r\n' explicitly. ๐
For convenience, the first call to fdevopen() that opens a stream for reading will cause the resulting stream to be aliased to stdin. Likewise, the first call to fdevopen() that opens a stream for writing will cause the resulting stream to be aliased to both, stdout, and stderr. Thus, if the open was done with both, read and write intent, all three standard streams will be identical. Note that these aliases are indistinguishable from each other, thus calling fclose() on such a stream will also effectively close all of its aliases (note 3). ๐
It is possible to tie additional user data to a stream, using fdev_set_udata(). The backend put and get functions can then extract this user data using fdev_get_udata(), and act appropriately. For example, a single put function could be used to talk to two different UARTs that way, or the put and get functions could keep internal state between calls there. ๐
๐ Format strings in flash ROM ๐
All the printf and scanf family functions come in two flavours: the standard name, where the format string is expected to be in SRAM, as well as a version with the suffix _P where the format string is expected to reside in the flash ROM. The macro PSTR (explained in <avr/pgmspace.h>: Program Space Utilities) becomes very handy for declaring these format strings. โญ
๐ Running stdio without malloc() ๐
By default, fdevopen() requires malloc(). As this is often not desired in the limited environment of a microcontroller, an alternative option is provided to run completely without malloc(). ๐ง
The macro fdev_setup_stream() is provided to prepare a user-supplied FILE buffer for operation with stdio. ๐
๐ Example ๐
Check out this example, bestie:
#include <stdio.h>
static int uart_putchar(char c, FILE *stream);
static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
_FDEV_SETUP_WRITE);
static int
uart_putchar(char c, FILE *stream)
{
if (c == '0) ', stream);
uart_putchar('
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
int
main(void)
{
init_uart();
stdout = &mystdout;
printf("Hello, world!0);
return 0;
}
This example uses the initializer form FDEV_SETUP_STREAM() rather than the function-like fdev_setup_stream(), so all data initialization happens during C start-up. โจ
If streams initialized that way are no longer needed, they can be destroyed by first calling the macro fdev_close(), and then destroying the object itself. No call to fclose() should be issued for these streams. While calling fclose() itself is harmless, it will cause an undefined reference to free() and thus cause the linker to link the malloc module into the application. ๐ซถ
๐ Notes ๐
Note 1:
It might have been possible to implement a device abstraction that is compatible with fopen() but since this would have required to parse a string, and to take all the information needed either out of this string, or out of an additional table that would need to be provided by the application, this approach was not taken. ๐
Note 2:
This basically follows the Unix approach: if a device such as a terminal needs special handling, it is in the domain of the terminal device driver to provide this functionality. Thus, a simple function suitable as put() for fdevopen() that talks to a UART interface might look like this: ๐
int
uart_putchar(char c, FILE *stream)
{
if (c == '0) ', stream);
uart_putchar('
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
Note 3:
This implementation has been chosen because the cost of maintaining an alias is considerably smaller than the cost of maintaining full copies of each stream. Yet, providing an implementation that offers the complete set of standard streams was deemed to be useful. Not only that writing printf() instead of fprintf(mystream, ...) saves typing work, but since avr-gcc needs to resort to pass all arguments of variadic functions on the stack (as opposed to passing them in registers for functions that take a fixed number of parameters), the ability to pass one parameter less by implying stdin or stdout will also save some execution time. ๐ฅ
โจ Macro Definition Documentation โจ
๐ #define _FDEV_EOF (-2)
The return code for when a device read hits an end-of-file sitch. ๐ซถ
You'd use this in the get function of fdevopen().
๐ #define _FDEV_ERR (-1)
The return code for when a device read hits an error sitch. ๐ญ
You'd use this in the get function of fdevopen().
๐ #define _FDEV_SETUP_READ __SRD
fdev_setup_stream() with read intent, bestie.
๐ #define _FDEV_SETUP_RW (__SRD|__SWR)
fdev_setup_stream() with read/write intent. Both vibes at once, no cap.
๐ #define _FDEV_SETUP_WRITE __SWR
fdev_setup_stream() with write intent.
๐ #define EOF (-1)
EOF declares the value that gets returned by a whole bunch of standard IO functions when something goes wrong. And listen โ since the AVR platform (as of rn) doesn't have an abstraction for actual files, its whole "end of file" origin story is lowkey meaningless here. It's just the error value, periodt.
๐ #define fdev_close()
This macro frees up any library resources that might be associated with stream. You should call it when stream isn't needed anymore, right before your app is about to destroy the stream object itself. โจ
(Currently, this macro evaluates to nothing, but that might change in future versions of the library. So like, call it anyway, bestie. Future you says thanks. ๐ )
๐ #define fdev_get_udata(stream) ((stream)->udata)
This macro retrieves a pointer to user defined data from a FILE stream object. Grab your stuff back, girl. ๐
๐ #define fdev_set_udata(stream, u) do { (stream)->udata = u; } while(0)
This macro inserts a pointer to user defined data into a FILE stream object.
The user data is super useful for tracking state in the put and get functions you hand over to fdevopen(). iykyk ๐
๐ #define fdev_setup_stream(stream, put, get, rwflag)
Okay so this sets up a user-supplied buffer as an stdio stream. What it does: it takes a user-supplied buffer stream, and sets it up as a stream that's valid for stdio operations โ basically like one you'd have gotten dynamically from fdevopen(). The buffer you're setting up must be of type FILE. ๐ฆ
The arguments put and get are identical to the ones you'd need to pass to fdevopen().
The rwflag argument can take one of the values _FDEV_SETUP_READ, _FDEV_SETUP_WRITE, or _FDEV_SETUP_RW โ for read, write, or read/write intent, respectively.
Note: No assignments to the standard streams will be performed byfdev_setup_stream(). If you wanna use standard streams, the user has to assign them. Also see the section under Running stdio withoutmalloc(). ๐
๐ #define FDEV_SETUP_STREAM(put, get, rwflag)
Initializer for a user-supplied stdio stream. This macro acts similar to fdev_setup_stream(), except it's meant to be used as the initializer of a variable of type FILE. ๐ธ
The remaining arguments are used exactly as explained in fdev_setup_stream().
๐ #define getc(__stream) fgetc(__stream)
The macro getc used to be a "fast" macro implementation doing the exact same thing as fgetc(). But for space constraints, in avr-libc it's literally just an alias for fgetc. Glow-down, not glow-up. ๐
๐ #define getchar(void) fgetc(stdin)
The macro getchar reads a character from stdin. Return values and error handling are identical to fgetc(). ๐
๐ #define putc(__c, __stream) fputc(__c, __stream)
The macro putc used to be a "fast" macro implementation doing the exact same thing as fputc(). But again, space constraints โ in avr-libc it's just an alias for fputc. ๐
๐ #define putchar(__c) fputc(__c, stdout)
The macro putchar sends character c to stdout. โจ
๐ #define stderr (__iob[2])
Stream destined for error output. Unless you specifically assign it otherwise, it's identical to stdout. ๐ญ
If stderr should point to another stream, you must explicitly assign it the result of another fdevopen() โ without closing the previous stderr (since that would also close stdout). Do not do that, bestie. That's a no. ๐
๐ #define stdin (__iob[0])
Stream that's gonna be used as an input stream by the simplified functions that don't take a stream argument.
The first stream opened with read intent using fdevopen() gets assigned to stdin. ๐
๐ #define stdout (__iob[1])
Stream that's gonna be used as an output stream by the simplified functions that don't take a stream argument.
The first stream opened with write intent using fdevopen() gets assigned to both, stdin, and stderr. (Yes, both. That's what it says. ๐)
๐ Typedef Documentation ๐
๐ฆ typedef struct __file FILE
FILE is the opaque structure that gets passed around between the various standard IO functions. Mysterious. Iconic. We don't look inside. ๐
๐ฅ Function Documentation ๐ฅ
โญ void clearerr (FILE * __stream)
Clear the error and end-of-file flags of stream. Reset the vibe. โจ
โญ int fclose (FILE * __stream)
This function closes stream, and disallows any further IO to and from it. Bye girl. ๐
When you're using fdevopen() to set up the stream, you need to call fclose() in order to free the internal resources that got allocated.
If the stream was set up using fdev_setup_stream() or FDEV_SETUP_STREAM(), use fdev_close() instead. (Different girl, different function. ๐)
It currently always returns 0 (for success).
โญ FILE* fdevopen (int(*)(char, FILE *) put, int(*)(FILE *) get)
This function is a replacement for fopen().
It opens a stream for a device where the actual device implementation has to be provided by the application. If it succeeds, you get a pointer to the structure for the opened stream. Reasons it might fail currently include: neither the put nor the get argument was provided (so you're trying to open a stream with no IO intent at all, girl what), or there isn't enough dynamic memory available to establish a new stream. ๐
If the put function pointer is provided, the stream opens with write intent. The function you pass as put shall take two arguments โ the first a character to write to the device, and the second a pointer to FILE โ and shall return 0 if the output was successful, and a nonzero value if the character couldn't be sent to the device.
If the get function pointer is provided, the stream opens with read intent. The function you pass as get shall take a pointer to FILE as its single argument, and return one character from the device, passed as an int type. If an error occurs while trying to read from the device, it shall return _FDEV_ERR. If an end-of-file condition was reached while reading from the device, _FDEV_EOF shall be returned.
If both functions are provided, the stream opens with read and write intent. Main character energy. ๐
The first stream opened with read intent gets assigned to stdin, and the first one opened with write intent gets assigned to both, stdout and stderr.
fdevopen() uses calloc() (and thus malloc()) in order to allocate the storage for the new stream.
Note: If the macro__STDIO_FDEVOPEN_COMPAT_12is declared before including<stdio.h>, a function prototype forfdevopen()will be chosen that is backwards compatible with avr-libc version 1.2 and before. This is solely intended for providing a simple migration path without needing to immediately change all your source code. Do not use for new code. Fr fr, don't. ๐ซ
โญ int feof (FILE * __stream)
Test the end-of-file flag of stream. Heads up: this flag can only be cleared by a call to clearerr(). ๐
โญ int ferror (FILE * __stream)
Test the error flag of stream. Same deal โ this flag can only be cleared by a call to clearerr().
โญ int fflush (FILE * stream)
Flush stream.
This is a null operation provided for source-code compatibility only, since the standard IO implementation currently doesn't perform any buffering. It's giving "we have flushing at home". ๐ซถ
โญ int fgetc (FILE * __stream)
The function fgetc reads a character from stream. It returns the character, or EOF in case end-of-file was encountered or an error occurred. You must use feof() or ferror() to tell those two situations apart. Don't guess, bestie. ๐ญ
โญ char* fgets (char * __str, int __size, FILE * __stream)
Read at most size - 1 bytes from stream, until a newline character was encountered, and store the characters in the buffer pointed to by str. Unless an error was encountered while reading, the string will then be terminated with a NUL character.
If an error was encountered, the function returns NULL and sets the error flag of stream, which you can test using ferror(). Otherwise, a pointer to the string gets returned. โจ
โญ int fprintf (FILE * __stream, const char * __fmt, ...)
The function fprintf performs formatted output to stream. See vfprintf() for details.
โญ int fprintf_P (FILE * __stream, const char * __fmt, ...)
Variant of fprintf() that uses a fmt string residing in program memory. ๐ง
โญ int fputc (int __c, FILE * __stream)
The function fputc sends the character c (though it's given as type int) to stream. It returns the character, or EOF in case an error occurred.
โญ int fputs (const char * __str, FILE * __stream)
Write the string pointed to by str to stream stream.
Returns 0 on success and EOF on error.
โญ int fputs_P (const char * __str, FILE * __stream)
Variant of fputs() where str resides in program memory. ๐
โญ size_t fread (void * __ptr, size_t __size, size_t __nmemb, FILE * __stream)
Read nmemb objects, size bytes each, from stream, to the buffer pointed to by ptr.
Returns the number of objects successfully read โ i.e. nmemb โ unless an input error occured or end-of-file was encountered. You must use feof() and ferror() to tell those two conditions apart. ๐
โญ int fscanf (FILE * __stream, const char * __fmt, ...)
The function fscanf performs formatted input, reading the input data from stream.
See vfscanf() for details.
โญ int fscanf_P (FILE * __stream, const char * __fmt, ...)
Variant of fscanf() using a fmt string in program memory. ๐
โญ size_t fwrite (const void * __ptr, size_t __size, size_t __nmemb, FILE * __stream)
Write nmemb objects, size bytes each, to stream. The first byte of the first object is referenced by ptr.
Returns the number of objects successfully written โ i.e. nmemb โ unless an output error occured.
โญ char* gets (char * __str)
Similar to fgets(), except it operates on stream stdin, and the trailing newline (if any) will not be stored in the string. It's the caller's responsibility to provide enough storage to hold the characters read. So like, be careful, bestie. ๐
โญ int printf (const char * __fmt, ...)
The function printf performs formatted output to stream stdout. See vfprintf() for details. โจ
โญ int printf_P (const char * __fmt, ...)
Variant of printf() that uses a fmt string residing in program memory.
โญ int puts (const char * __str)
Write the string pointed to by str, and a trailing newline character, to stdout. ๐ธ
โญ int puts_P (const char * __str)
Variant of puts() where str resides in program memory.
โญ int scanf (const char * __fmt, ...)
The function scanf performs formatted input from stream stdin.
See vfscanf() for details.
โญ int scanf_P (const char * __fmt, ...)
Variant of scanf() where fmt resides in program memory. ๐
โญ int snprintf (char * __s, size_t __n, const char * __fmt, ...)
Like sprintf(), but instead of assuming s to be of infinite size, no more than n characters (including the trailing NUL character) will be converted to s.
Returns the number of characters that would have been written to s if there were enough space. (So it tells you the truth even when it can't fit it all. Honest queen. ๐)
snprintf_P()
int snprintf_P (char * __s, size_t __n, const char * __fmt, ...)
It's the snprintf() vibe, but the fmt string is living its best life in program memory ๐ง โจ
sprintf()
int sprintf (char * __s, const char * __fmt, ...)
Basically printf(), except the formatted characters get yeeted into the string s instead of a stream ๐
sprintf_P()
int sprintf_P (char * __s, const char * __fmt, ...)
Same energy as sprintf(), but once again the fmt string is chilling in program memory ๐พ๐
sscanf()
int sscanf (const char * __buf, const char * __fmt, ...)
So sscanf does formatted input, and it reads that input data straight out of the buffer that buf is pointing at ๐ฅ (like, it's the reading-from-a-string girlie)
Want the deets? Go look at vfscanf() โ that's where the tea is โ
sscanf_P()
int sscanf_P (const char * __buf, const char * __fmt, ...)
sscanf() again, but the fmt string is a program-memory girlie ๐
ungetc()
int ungetc (int __c, FILE * __stream)
okay so ungetc() takes the character c (converted to an unsigned char) and pushes it back onto the input stream that stream points at ๐๐ซ And the pushed-back character? Yeah, the next read on that stream is gonna hand it right back to you. Iconic behavior, no notes.
Currently, only a single character can be pushed back onto the stream. That's the limit bestie, don't get greedy ๐
Return value tea: ungetc() returns the character that got pushed back after the conversion, or EOF if the whole operation fails ๐ญ And heads up โ if the value of the argument c character equals EOF, the operation will fail and the stream stays exactly how it was. No changes, periodt. ๐
vfprintf()
int vfprintf (FILE * __stream, const char * __fmt, va_list __ap)
vfprintf is literally the central facility of the whole printf family ๐ Like, the main character. It outputs values to stream under the control of a format string that gets passed in fmt, and the actual values to print come in as a variable argument list, ap โจ
Returns: the number of characters written to stream, or EOF if there's an error. And rn, that error basically only happens if stream wasn't opened with write intent ๐ซโ๏ธ
๐ธ The Format String, explained by me, your bestie ๐ธ
The format string is made up of zero or more directives:
- Ordinary characters (anything that is not
%) โ these get copied to the output stream unchanged, no drama ๐ - Conversion specifications โ each one fetches zero or more subsequent arguments. Every conversion specification starts with the
%character. And the arguments must properly correspond (after type promotion, okay?!) with the conversion specifier ๐
After the %, here's what shows up, in this exact sequence:
- Zero or more of these flags:
#โ the value gets converted to an "alternate form". Forc,d,i,s, anduconversions, this option does nothing, sorry. Foroconversions, the precision of the number gets increased to force the first character of the output string to be a zero (except when a zero value is printed with an explicit precision of zero). ForxandXconversions, a non-zero result gets the string0x(or0XforXconversions) prepended to it โจ0(zero) โ Zero padding. For all conversions, the converted value gets padded on the left with zeros instead of blanks. But if a precision is given with a numeric conversion (d,i,o,u,i,x, andX), the0flag is ignored ๐ซ-โ a negative field width flag; the converted value gets left-adjusted on the field boundary. So it's padded on the right with blanks, instead of on the left with blanks or zeros. And a-overrides a0if you give both, so pick a lane bestie ๐+โ a sign must always be placed before a number produced by a signed conversion. A+overrides a space if both are used ๐
- An optional decimal digit string specifying a minimum field width ๐ If the converted value has fewer characters than the field width, it gets padded with spaces on the left (or right, if the left-adjustment flag has been given) to fill out that field width.
- An optional precision, written as a period
.followed by an optional digit string. If the digit string is omitted, the precision is taken as zero. This gives the minimum number of digits to appear ford,i,o,u,x, andXconversions, or the maximum number of characters to be printed from a string forsconversions ๐ - An optional
lorhlength modifier, which specifies that the argument for thed,i,o,u,x, orXconversion is along intrather thanint. Thehis ignored, sinceshort intis equivalent toint๐คทโโ๏ธ - A character that specifies the type of conversion to be applied.
๐ The conversion specifiers and what they mean ๐
diouxXโ theint(or appropriate variant) argument gets converted to signed decimal (dandi), unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (xandX) notation. The lettersabcdefare used forxconversions; the lettersABCDEFare used forXconversions. The precision, if there is one, gives the minimum number of digits that must appear; if the converted value needs fewer digits, it gets padded on the left with zeros ๐งฎpโ thevoid *argument is taken as an unsigned integer, and converted similarly to how a%#xcommand would do it ๐ฏcโ theintargument gets converted to anunsigned char, and the resulting character is written โ๏ธsโ thechar *argument is expected to be a pointer to an array of character type (aka a pointer to a string). Characters from the array are written up to (but not including) a terminatingNULcharacter; if a precision is specified, no more than the number specified get written. If a precision is given, no null character needs to be present; but if the precision isn't specified, or is greater than the size of the array, the array must contain a terminatingNULcharacter ๐จ%โ a%gets written. No argument is converted. The complete conversion specification is%%๐eEโ thedoubleargument gets rounded and converted into the format[-]d.dddeยฑdd, where there's one digit before the decimal-point character and the number of digits after it equals the precision. If the precision is missing, it's taken as 6; if the precision is zero, no decimal-point character appears. AnEconversion uses the letterE(rather thane) to introduce the exponent. The exponent always contains two digits; if the value is zero, the exponent is00๐ฌfFโ thedoubleargument gets rounded and converted to decimal notation in the format[-]ddd.ddd, where the number of digits after the decimal-point character equals the precision specification. If the precision is missing, it's taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it ๐gGโ thedoubleargument gets converted in stylefore(orForEforGconversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it's treated as 1. Styleeis used if the exponent from its conversion is less than-4or greater than or equal to the precision. Trailing zeros get removed from the fractional part of the result; a decimal point appears only if it's followed by at least one digit โ๏ธSโ just like thesformat, except the pointer is expected to point to a program-memory (ROM) string instead of a RAM string ๐ง
In no case does a non-existent or small field width cause truncation of a numeric field โ if the result of a conversion is wider than the field width, the field gets expanded to contain the conversion result. The math will not be silenced ๐ช
๐ฆ The three flavours of vfprintf() ๐ฆ
Since the full implementation of all the features above becomes fairly large, you can pick between three different flavours of vfprintf() using linker options ๐
- The default
vfprintf()implements all the mentioned functionality except floating point conversions. - There's a minimized version of
vfprintf()that only implements the very basic integer and string conversion facilities โ and only the#additional option can be specified using conversion flags (those flags are parsed correctly from the format specification, but then simply ignored). You ask for this version with these compiler options:
-Wl,-u,vfprintf -lprintf_min
- And if you need the full functionality including the floating point conversions, these are the options you want:
-Wl,-u,vfprintf -lprintf_flt -lm
โ ๏ธ Limitations โ ๏ธ
- The specified width and precision can be at most
255. That's the ceiling bestie, don't test it ๐
๐ Notes ๐
notes time, and oop โ there's more coming, so stay with me ๐
okay so continuing from where we left off, bestie ๐ โ here are the vfprintf() caveats you need to know:
- for floating-point conversions, if you link the default or minimized version of
vfprintf(), the symbol?will be output and thedoubleargument will be skipped. so your output below will not be crashed. For the default version, the width field and the 'pad to left' (symbol minus) option will work in this case. ๐ - the
hhlength modifier is ignored (thecharargument is promoted toint). more exactly, this realization does not check the number ofhsymbols. ๐ - but the
lllength modifier will abort the output, because this realization does not operatelong longarguments. ๐ - the variable width or precision field (an asterisk
*symbol) is not realized and will abort the output. ๐ญ
lowkey important: those aborts are real, so watch your format strings, bestie.
int vfprintf_P (FILE * __stream, const char * __fmt, va_list __ap)โ it's givingvfprintf()but thefmtstring lives in program memory. โจ
int vfscanf (FILE * stream, const char * fmt, va_list ap)โ formatted input, bestie. This function is literally the heart of thescanffamily of functions. ๐
Characters are read from stream and processed in a way described by fmt. Conversion results will be assigned to the parameters passed via ap. The format string fmt is scanned for conversion specifications. Anything that doesn't comprise a conversion specification is taken as text that is matched literally against the input. White space in the format string will match any white space in the data (including none), all other characters match only itself. Processing is aborted as soon as the data and format string no longer match, or there is an error or end-of-file condition on stream.
Most conversions skip leading white space before starting the actual conversion.
Conversions are introduced with the character %. Possible options can follow the %:
- a
*indicating that the conversion should be performed but the conversion result is to be discarded; no parameters will be processed fromap, - the character
hindicating that the argument is a pointer toshort int(rather thanint), - the 2 characters
hhindicating that the argument is a pointer tochar(rather thanint). - the character
lindicating that the argument is a pointer tolong int(rather thanint, for integer type conversions), or a pointer tofloat(for floating point conversions),
In addition, a maximal field width may be specified as a nonzero positive decimal integer, which will restrict the conversion to at most this many characters from the input stream. This field width is limited to at most 255 characters which is also the default value (except for the c conversion that defaults to 1).
The following conversion flags are supported:
%โ Matches a literal%character. This is not a conversion.dโ Matches an optionally signed decimal integer; the next pointer must be a pointer toint.iโ Matches an optionally signed integer; the next pointer must be a pointer toint. The integer is read in base 16 if it begins with0xor0X, in base 8 if it begins with0, and in base 10 otherwise. Only characters that correspond to the base are used.oโ Matches an octal integer; the next pointer must be a pointer tounsigned int.uโ Matches an optionally signed decimal integer; the next pointer must be a pointer tounsigned int.xโ Matches an optionally signed hexadecimal integer; the next pointer must be a pointer tounsigned int.fโ Matches an optionally signed floating-point number; the next pointer must be a pointer tofloat.e,g,F,E,Gโ Equivalent tof.sโ Matches a sequence of non-white-space characters; the next pointer must be a pointer tochar, and the array must be large enough to accept all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, whichever occurs first.cโ Matches a sequence of width count characters (default1); the next pointer must be a pointer tochar, and there must be enough room for all the characters (no terminating NUL is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.[โ Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer tochar, and there must be enough room for all the characters in the string, plus a terminating NUL character. The usual skip of leading white space is suppressed. The string is to be made up of characters in (or not in) a particular set; the set is defined by the characters between the open bracket[character and a close bracket]character. The set excludes those characters if the first character after the open bracket is a circumflex^. To include a close bracket in the set, make it the first character after the open bracket or the circumflex; any other position will end the set. The hyphen character-is also special; when placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make it the last character before the final close bracket. For instance,[^]0-9-]means the set of everything except close bracket, zero through nine, and hyphen. The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out. Note that usage of this conversion enlarges the stack expense.pโ Matches a pointer value (as printed bypinprintf()); the next pointer must be a pointer tovoid.nโ Nothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer toint. This is not a conversion, although it can be suppressed with the*flag.
These functions return the number of input items assigned, which can be fewer than provided for, or even zero, in the event of a matching failure. Zero indicates that, while there was input available, no conversions were assigned; typically this is due to an invalid input character, such as an alphabetic character for a d conversion. The value EOF is returned if an input failure occurs before any conversion such as an end-of-file occurs. If an error or end-of-file occurs after conversion has begun, the number of conversions which were successfully completed is returned.
By default, all the conversions described above are available except the floating-point conversions and the width is limited to 255 characters. The float-point conversion will be available in the extended version provided by the library libscanf_flt.a. Also in this case the width is not limited (exactly, it is limited to 65535 characters). To link a program against the extended version, use the following compiler flags in the link stage:
-Wl,-u,vfscanf -lscanf_flt -lm
A third version is available for environments that are tight on space. In addition to the restrictions of the standard one, this version implements no %[ specification. This version is provided in the library libscanf_min.a, and can be requested using the following options in the link stage:
-Wl,-u,vfscanf -lscanf_min -lm
int vfscanf_P (FILE * __stream, const char * __fmt, va_list __ap)โ variant ofvfscanf()using afmtstring in program memory. ๐งint vprintf (const char * __fmt, va_list __ap)โ performs formatted output to streamstdout, taking a variable argument list as invfprintf(). Seevfprintf()for details. โจint vscanf (const char * __fmt, va_list __ap)โ performs formatted input from streamstdin, taking a variable argument list as invfscanf(). Seevfscanf()for details. ๐int vsnprintf (char * __s, size_t __n, const char * __fmt, va_list ap)โ likevsprintf(), but instead of assumingsto be of infinite size, no more thanncharacters (including the trailing NUL character) will be converted tos. Returns the number of characters that would have been written tosif there were enough space. ๐int vsnprintf_P (char * __s, size_t __n, const char * __fmt, va_list ap)โ variant ofvsnprintf()that uses afmtstring that resides in program memory. ๐ธint vsprintf (char * __s, const char * __fmt, va_list ap)โ likesprintf()but takes a variable argument list for the arguments. ๐int vsprintf_P (char * __s, const char * __fmt, va_list ap)โ variant ofvsprintf()that uses afmtstring that resides in program memory. ๐ฆ
๐ Author ๐
Generated automatically by Doxygen for avr-libc from the source code. (yes bestie, that's the whole author section ๐ )
Version 2.1.0 โ dated Sat Jan 29 2022 โ from the avr_stdio(3) manual page. bye bestie, go slay some embedded C! ๐โจ๐
๐ฆ where this page comes from
- fedora 43: avr-libc 2.2.1-3.fc43 ยท BSD-3-Clause
- fedora 44: avr-libc 2.2.1-5.fc44 ยท BSD-3-Clause
- opensuse-leap 16.0: avr-libc 2.1.0-bp160.1.33 ยท BSD-3-Clause
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms