avr_stdio(3avr)

πŸ’… avr_stdio(3avr) β€” Standard IO facilities πŸ’…

okay so bestie, sit down, hydrate, because this is avr_stdio(3avr) and it's lowkey one of the most important pages in the whole AVR-LibC situation. it's literally the <stdio.h> header doing its thing on a microcontroller with no operating system, no files, and honestly not a lot of RAM. iconic behavior fr fr. let's get into it 🫢


🌸 NAME 🌸

avr_stdio β€” <stdio.h>: Standard IO facilities


✨ SYNOPSIS ✨

πŸŽ€ Macros

#define stdin   (__iob[0])
#define stdout   (__iob[1])
#define stderr   (__iob[2])
#define EOF   (-1)
#define fdev_set_udata(stream,  u)
#define fdev_get_udata(stream)
#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)
#define putchar(__c)
#define getc(__stream)
#define getchar()

🧚 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

bestie. this file declares the standard IO facilities that AVR-LibC implements. and because the underlying hardware is built different (in the sense that it's, like, a chip), only a limited subset of standard IO is here. there is no actual file implementation available, so only device IO can be performed. and since there's no operating system at all, your application has to supply enough details about its devices to make them usable by the standard IO facilities. no OS is gonna do it for you, she doesn't exist πŸ’€

and because of space constraints, some functionality just straight up has not been implemented at all (like some of the printf conversions that were left out β€” gone, not invited).

but wait, potential user of this implementation, you deserve a warning: the printf and scanf families of functions? yeah, they're usually associated with presumably simple things like the famous "Hello, world!" program, but they are actually fairly complex, which causes their inclusion to eat up a fair amount of code space. also, they are not fast, because of the nature of interpreting the format string at run-time. so whenever possible, resorting to the (sometimes non-standard) predetermined conversion facilities that AVR-LibC offers will usually cost much less in terms of speed and code size. no cap ✨

πŸ”§ Tunable options for code size vs. feature set

to let programmers have a code size vs. functionality tradeoff, vfprintf() β€” which is literally 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 exact same thing applies to vfscanf() and the scanf family of functions. slay, choices.

🌈 Outline of the chosen API

so 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. they're just sitting there. waiting. πŸ™ˆ

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. the 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.

fr fr, that one matters.

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. so if the open was done with both, read and write intent, all three standard streams will be identical. and note that these aliases are indistinguishable from each other, so calling fclose() on such a stream will also effectively close all of its aliases (note 3). the way that they're all the same girl πŸ’…

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. keeping internal state? that's giving main character energy πŸŽ€

🌟 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
  • 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. obsessed with her. πŸ’–

πŸ“ Running stdio without malloc()

by default, fdevopen() requires malloc(). and since that 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. no malloc, no problem, we love a budget queen 🫢

🧁 Example

#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 == '\n')
    uart_putchar('\r', stream);
  loop_until_bit_is_set(UCSRA, UDRE);
  UDR = c;
  return 0;
}

int
main(void)
{
  init_uart();
  stdout = &mystdout;
  printf("Hello, world!\n");

  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. very set-it-and-forget-it of her.

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. and 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. so like, harmless but also not harmless. do not do it bestie 😭


πŸ’œ 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. she said no thank you πŸ’…

🌸 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 == '\n')
    uart_putchar('\r', stream);
  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. and 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. so it's cute and it's efficient. periodt πŸ’–


✨ Macro Definition Documentation ✨

okay bestie, this is the part where AVR-LibC hands you a whole bag of macros that make stdio actually work on a chip with, like, no filesystem πŸ’… here we go, one by one, no skipping.


  • _FDEV_EOF β€” value (-2)

This is the return code your device read function should give back when it hits an end-of-file condition. It's meant to be used in the get function you hand to fdevopen(). πŸ¦‹

  • _FDEV_ERR β€” value (-1)

And this one is the return code for an error condition while reading from a device. Also to be used in the get function of fdevopen(). So basically: _FDEV_ERR = something went wrong, _FDEV_EOF = we ran out of stuff to read. Periodt.

  • _FDEV_SETUP_READ β€” value __SRD

fdev_setup_stream() with read intent, that's it, that's the vibe.

  • _FDEV_SETUP_RW β€” value (__SRD|__SWR)

fdev_setup_stream() with read/write intent. Both directions, main character energy ✨

  • _FDEV_SETUP_WRITE β€” value __SWR

fdev_setup_stream() with write intent. Output only, we're not listening πŸ™ˆ

  • EOF β€” value (-1)

EOF declares the value that gets returned by various standard IO functions when there's an error. Now listen β€” since the AVR platform (currently) doesn't have any abstraction for actual files, its whole origin story as "end of file" is kind of meaningless here. It's just, like, the error number. no cap.

  • fdev_close()

This macro frees up any library resources that might be associated with stream. You should call it if stream is no longer needed, right before your application is going to destroy the stream object itself.

(Currently, this macro evaluates to nothing, but this might change in future versions of the library.) So like, call it anyway bestie, future-you will thank you πŸ’–
  • fdev_get_udata( stream) β€” Value:
((stream)->udata)

This macro retrieves a pointer to user defined data from a FILE stream object. Yours. Your data. Get it back. πŸŽ€

  • fdev_set_udata( stream, u) β€” Value:
do { (stream)->udata = u; } while(0)

This macro inserts a pointer to user defined data into a FILE stream object.

This user data is lowkey so useful for tracking state in the put and get functions you supply to the fdevopen() function. State tracking queen πŸ‘‘

  • FDEV_SETUP_STREAM( put, get, rwflag)

Initializer for a user-supplied stdio stream. This macro acts similar to fdev_setup_stream(), but it's the one you use as the initializer of a variable of type FILE.

The remaining arguments are to be used as explained in fdev_setup_stream(). iykyk.

  • fdev_setup_stream( stream, put, get, rwflag)

Setup a user-supplied buffer as an stdio stream. This macro takes a user-supplied buffer stream, and sets it up as a stream that's valid for stdio operations, similar to one that's been obtained dynamically from fdevopen(). The buffer you're setting up must be of type FILE.

The arguments put and get are identical to those that need to be passed 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 by fdev_setup_stream(). If standard streams are to be used, these need to be assigned by the user. See also under Running stdio without malloc(). So don't come for me when stdin is still NULL, bestie, that's on you πŸ™ˆ
  • getc( __stream) β€” Value:
fgetc(__stream)

The macro getc used to be a "fast" macro implementation, functionally identical to fgetc(). For space constraints, in AVR-LibC, it's just an alias for fgetc. Glow-down, not glow-up πŸ’€

  • getchar( void) β€” Value:
fgetc(stdin)

The macro getchar reads a character from stdin. Return values and error handling are identical to fgetc().

  • putc( __c, __stream) β€” Value:
fputc(__c, __stream)

The macro putc used to be a "fast" macro implementation, functionally identical to fputc(). For space constraints, in AVR-LibC, it's just an alias for fputc. Same story as getc, iconic behavior honestly.

  • putchar( __c) β€” Value:
fputc(__c, stdout)

The macro putchar sends character c to stdout. simple as that, slay ✨

  • stderr β€” value (__iob[2])

Stream destined for error output. Unless specifically assigned, it's identical to stdout.

If stderr should point to another stream, the result of another fdevopen() must be explicitly assigned to it without closing the previous stderr (since this would also close stdout). 🚨 big yikes if you get that wrong, so read it twice.

  • stdin β€” value (__iob[0])

Stream that will 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() will be assigned to stdin. first come, first served πŸ’…

  • stdout β€” value (__iob[1])

Stream that will 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() will be assigned to both, stdin, and stderr.


πŸ¦‹ Typedef Documentation πŸ¦‹

  • typedef struct __file FILE

FILE is the opaque structure that gets passed around between the various standard IO functions. Opaque = you don't get to peek inside, you just pass it along like a little note in class πŸ“


πŸ’– Function Documentation πŸ’–

here come the actual functions, buckle up bestie, there's a lot and every single one matters.


  • void clearerr (FILE * __stream) [extern]

Clear the error and end-of-file flags of stream. fresh start energy 🌸

  • int fclose (FILE * __stream) [extern]

This function closes stream, and disallows and further IO to and from it.

When you're using fdevopen() to setup the stream, a call to fclose() is needed in order to free the internal resources allocated.

If the stream has been set up using fdev_setup_stream() or FDEV_SETUP_STREAM(), use fdev_close() instead. Don't mix them up, okay? 😭

It currently always returns 0 (for success).

  • FILE * fdevopen (int(* put )(char, FILE *), int(* get )(FILE *))

This function is a replacement for fopen().

It opens a stream for a device where the actual device implementation needs to be provided by the application. If successful, a pointer to the structure for the opened stream is returned. Reasons for a possible failure currently include that neither the put nor the get argument have been provided β€” thus attempting to open a stream with no IO intent at all β€” or that insufficient dynamic memory is available to establish a new stream.

If the put function pointer is provided, the stream is opened with write intent. The function passed 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 could not be sent to the device.

If the get function pointer is provided, the stream is opened with read intent. The function passed 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 when 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 is opened with read and write intent. both. greedy. love that for us πŸ’…

The first stream opened with read intent is assigned to stdin, and the first one opened with write intent is assigned to both, stdout and stderr.

fdevopen() uses calloc() (und thus malloc()) in order to allocate the storage for the new stream.

Note β€” If the macro __STDIO_FDEVOPEN_COMPAT_12 is declared before including <stdio.h>, a function prototype for fdevopen() will be chosen that is backwards compatible with AVR-LibC version 1.2 and before. This is solely intented for providing a simple migration path without the need to immediately change all source code. Do not use for new code. 🚫 she's legacy, leave her in 2010.
  • int feof (FILE * __stream) [extern]

Test the end-of-file flag of stream. This flag can only be cleared by a call to clearerr().

  • int ferror (FILE * __stream) [extern]

Test the error flag of stream. This flag can only be cleared by a call to clearerr(). same deal, same rules πŸŽ€

  • int fflush (FILE * stream) [extern]

Flush stream.

This is a null operation provided for source-code compatibility only, as the standard IO implementation currently does not perform any buffering. so it's giving… nothing. but it's there, and that's what counts ✨

  • int fgetc (FILE * __stream) [extern]

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. The routines feof() or ferror() must be used to distinguish between both situations. don't guess, check 😀

  • char * fgets (char * __str, int __size, FILE * __stream) [extern]

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 can be tested using ferror(). Otherwise, a pointer to the string will be returned.

  • int fprintf (FILE * __stream, const char * __fmt, ...) [extern]

The function fprintf performs formatted output to stream. See vfprintf() for details.

  • int fprintf_P (FILE * __stream, const char * __fmt, ...) [extern]

Variant of fprintf() that uses a fmt string that resides in program memory. that _P suffix is your girl for flash strings πŸ’–

  • int fputc (int __c, FILE * __stream) [extern]

The function fputc sends the character c (though given as type int) to stream. It returns the character, or EOF in case an error occurred.

  • int fputs (const char * __str, FILE * __stream) [extern]

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) [extern]

Variant of fputs() where str resides in program memory.

  • size_t fread (void * __ptr, size_t __size, size_t __nmemb, FILE * __stream) [extern]

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. feof() and ferror() must be used to distinguish between these two conditions.

  • int fscanf (FILE * __stream, const char * __fmt, ...) [extern]

The function fscanf performs formatted input, reading the input data from stream.

See vfscanf() for details.

  • int fscanf_P (FILE * __stream, const char * __fmt, ...) [extern]

Variant of fscanf() using a fmt string in program memory.

  • size_t fwrite (const void * __ptr, size_t __size, size_t __nmemb, FILE * __stream) [extern]

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) [extern]

Similar to fgets() except that it will operate on stream stdin, and the trailing newline (if any) will not be stored in the string. It is the caller's responsibility to provide enough storage to hold the characters read. that's on you, provide the buffer 🫢

  • int printf (const char * __fmt, ...) [extern]

The function printf performs formatted output to stream stdout. See vfprintf() for details.

  • int printf_P (const char * __fmt, ...) [extern]

Variant of printf() that uses a fmt string that resides in program memory.

  • int puts (const char * __str) [extern]

Write the string pointed to by str, and a trailing newline character, to stdout. newline included for free, we love a generous icon πŸ‘‘

  • int puts_P (const char * __str) [extern]

Variant of puts() where str resides in program memory.

  • int scanf (const char * __fmt, ...) [extern]

The function scanf performs formatted input from stream stdin.

See vfscanf() for details.

  • int scanf_P (const char * __fmt, ...) [extern]

Variant of scanf() where fmt resides in program memory.

🫢 int snprintf (char * __s, size_t __n, const char * __fmt, ...) [extern]

So it's giving sprintf() energy, except sprintf() is out here assuming s is infinite and honestly bestie, nothing is. Here, no more than n characters (and yes, that count includes the trailing NUL character πŸŽ€) get converted into s.

It hands you back the number of characters that would have been written to s if there were enough space. Like, the receipts of how big it really wanted to be.


✨ int snprintf_P (char * __s, size_t __n, const char * __fmt, ...) [extern]

A variant of snprintf() that uses a fmt string chilling in program memory. That's the whole vibe. πŸ’…


🌸 int sprintf (char * __s, const char * __fmt, ...) [extern]

A variant of printf() that sends the formatted characters to the string s instead of, y'know, out into the world. Cozy. πŸ¦‹


πŸŽ€ int sprintf_P (char * __s, const char * __fmt, ...) [extern]

Variant of sprintf() that uses a fmt string that lives in program memory. Iconic behaviour, no notes. ⭐


πŸ’œ int sscanf (const char * __buf, const char * __fmt, ...) [extern]

sscanf does formatted input β€” it reads the input data straight out of the buffer that buf points to. πŸ”₯

For all the juicy details, go see vfscanf(). She's the main character, this one's just the remix.


πŸ’– int sscanf_P (const char * __buf, const char * __fmt, ...) [extern]

Variant of sscanf() using a fmt string in program memory. Obviously. πŸ’…


🧚 int ungetc (int __c, FILE * __stream) [extern]

ungetc() takes the character c (converted to an unsigned char, bestie) and pushes it back onto the input stream pointed to by stream. The pushed-back character will then be returned by a subsequent read on the stream. It's like hitting undo on a snack you already ate. πŸ“

Currently, only a single character can be pushed back onto the stream. One. Uno. That's the limit, periodt.

ungetc() returns the character pushed back after the conversion, or EOF if the operation fails. And like β€” if the value of the argument c equals EOF, the operation will fail and the stream stays completely unchanged. Not a single thing moves. πŸ’€


πŸ‘‘ int vfprintf (FILE * __stream, const char * __fmt, va_list __ap) [extern]

vfprintf is the central facility of the whole printf family β€” the mother of the group chat, fr fr. It outputs values to stream under the control of a format string passed in fmt. The actual values to print get passed in as a variable argument list ap.

vfprintf returns the number of characters written to stream, or EOF in case of an error. Currently, that only happens if stream hasn't been opened with write intent. 🚫

The format string is composed of zero or more directives: ordinary characters (anything that isn't %), which get copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the % character. The arguments must properly correspond (after type promotion, bestie, we don't skip steps) with the conversion specifier. After the %, the following appear in sequence:

  • Zero or more of the following flags:
    • # β€” the value should be converted to an "alternate form". For c, d, i, s, and u conversions, this option has no effect. For o conversions, the precision of the number is increased to force the first character of the output string to be a zero (except if a zero value is printed with an explicit precision of zero). For x and X conversions, a non-zero result gets the string 0x (or 0X for X conversions) prepended to it. Spicy. ✨
    • 0 (zero) β€” zero padding. For all conversions, the converted value is padded on the left with zeros rather than blanks. If a precision is given with a numeric conversion (d, i, o, u, i, x, and X), the 0 flag is ignored. πŸ’…
    • - β€” a negative field width flag; the converted value is to be left adjusted on the field boundary. The converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given. She wins, always. πŸ‘‘
    • (this bullet is just… empty in the original, bestie πŸ’€ no cap, we're leaving it exactly as we found it β€” vibe check says typo, we don't editorialize)
    • + β€” a sign must always be placed before a number produced by a signed conversion. A + overrides a space if both are used. So demanding. We love her. 🫢
  • An optional decimal digit string specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given) to fill out the field width.
  • An optional precision, in the form of 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 for d, i, o, u, x, and X conversions, or the maximum number of characters to be printed from a string for s conversions.
  • An optional l or h length modifier, that specifies that the argument for the d, i, o, u, x, or X conversion is a "long int" rather than int. The h is ignored, as "short int" is equivalent to int.
  • A character that specifies the type of conversion to be applied.

The conversion specifiers and their meanings are:

  • diouxX β€” the int (or appropriate variant) argument is converted to signed decimal (d and i), unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation. The letters "abcdef" are used for x conversions; the letters "ABCDEF" are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. πŸ”’
  • p β€” the void * argument is taken as an unsigned integer, and converted similarly as a %#x command would do.
  • c β€” the int argument is converted to an "unsigned char", and the resulting character is written.
  • s β€” the "char *" argument is expected to be a pointer to an array of character type (a pointer to a string, bestie). Characters from the array are written up to (but not including) a terminating NUL character; if a precision is specified, no more than the number specified are written. If a precision is given, no null character need be present; if the precision is not specified, or is greater than the size of the array, the array must contain a terminating NUL character. That's not a suggestion, that's the law. 🚨
  • % β€” a % is written. No argument is converted. The complete conversion specification is "%%". Cute little duo. πŸ’•
  • eE β€” the double argument is rounded and converted in the format "[-]d.dddeΒ±dd" where there is one digit before the decimal-point character and the number of digits after it is equal to the precision; if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses the letter 'E' (rather than 'e') to introduce the exponent. The exponent always contains two digits; if the value is zero, the exponent is 00.
  • fF β€” the double argument is rounded and converted to decimal notation in the format "[-]ddd.ddd", where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is 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 β€” the double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit. She's picky but she's right. ✨
  • S β€” similar to the s format, 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 is expanded to contain the conversion result. Numbers don't get chopped, bestie. Not on our watch. πŸ’…


Since the full implementation of all the mentioned features becomes fairly large (she's a big girl), three different flavours of vfprintf() can be selected using linker options. The default vfprintf() implements all the mentioned functionality except floating point conversions. A minimized version of vfprintf() is available that only implements the very basic integer and string conversion facilities, but only the # additional option can be specified using conversion flags (these flags are parsed correctly from the format specification, but then simply ignored β€” they show up to the party and then sit in the corner πŸ™ˆ). This version can be requested using the following compiler options:

-Wl,-u,vfprintf -lprintf_min

If the full functionality including the floating point conversions is required, the following options should be used:

-Wl,-u,vfprintf -lprintf_flt -lm

Limitations:

  • The specified width and precision can be at most 255. That's the ceiling, bestie. πŸŽ€

Notes:

  • For floating-point conversions, if you link the default or minimized version of vfprintf(), the symbol ? will be output and the double argument 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 hh length modifier is ignored (char argument is promoted to int). More exactly, this realization does not check the number of h symbols. She's not counting, and honestly, relatable. πŸ’€
  • But the ll length modifier will abort the output, as this realization does not operate on long long arguments. Do not pass her a long long. She will not survive it. 😭
  • The variable width or precision field (an asterisk * symbol) is not realized and will abort the output. Rip. πŸͺ¦

πŸ¦‹ int vfprintf_P (FILE * __stream, const char * __fmt, va_list __ap) [extern]

Variant of vfprintf() that uses a fmt string that resides in program memory. Same icon, different storage class. πŸ’…


⭐ int vfscanf (FILE * stream, const char * fmt, va_list ap) [extern]

Formatted input. This function is the heart of the scanf family of functions β€” the moment, the blueprint, the whole era. πŸ‘‘

Characters are read from stream and processed in a way described by fmt. Conversion results get 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 β€” she's flexible like that), and all other characters match only themselves. Processing is aborted as soon as the data and format string no longer match, or there's an error or end-of-file condition on stream. She's done when she's done. πŸŽ€

Most conversions skip leading white space before starting the actual conversion. Politeness. We stan. 🫢

Conversions are introduced with the character %. Possible options can follow the %:

and you can also sprinkle some modifier magic on your conversions, bestie ✨:

  • a * indicating that the conversion should be performed but the conversion result is to be discarded; no parameters will be processed from ap,
  • the character h indicating that the argument is a pointer to short int (rather than int),
  • the 2 characters hh indicating that the argument is a pointer to char (rather than int).
  • the character l indicating that the argument is a pointer to long int (rather than int, for integer type conversions), or a pointer to float (for floating point conversions),

Also, you can set a maximum field width as a nonzero positive decimal integer β€” it'll cap the conversion to at most that many characters from the input stream πŸ›‘. This field width is limited to at most 255 characters, which is also the default (except for the c conversion that defaults to 1).

The following conversion flags are supported, no cap:

  • % β€” Matches a literal % character. This is not a conversion. πŸ’―
  • d β€” Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
  • i β€” Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, 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 to unsigned int.
  • u β€” Matches an optionally signed decimal integer; the next pointer must be a pointer to unsigned int.
  • x β€” Matches an optionally signed hexadecimal integer; the next pointer must be a pointer to unsigned int.
  • f β€” Matches an optionally signed floating-point number; the next pointer must be a pointer to float.
  • e, g, F, E, G β€” Equivalent to f.
  • s β€” Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, 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 (default 1); the next pointer must be a pointer to char, 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 to char, 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 by p in printf()); the next pointer must be a pointer to void.
  • 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 to int. 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) [extern]

Variant of vfscanf() using a fmt string in program memory. 🧠

int vprintf (const char * __fmt, va_list __ap) [extern]

The function vprintf performs formatted output to stream stdout, taking a variable argument list as in vfprintf().

See vfprintf() for details. πŸ’¬

int vscanf (const char * __fmt, va_list __ap) [extern]

The function vscanf performs formatted input from stream stdin, taking a variable argument list as in vfscanf().

See vfscanf() for details. ⌨️

int vsnprintf (char * __s, size_t __n, const char * __fmt, va_list ap) [extern]

Like vsprintf(), 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. πŸ“

int vsnprintf_P (char * __s, size_t __n, const char * __fmt, va_list ap) [extern]

Variant of vsnprintf() that uses a fmt string that resides in program memory. 🧠

int vsprintf (char * __s, const char * __fmt, va_list ap) [extern]

Like sprintf() but takes a variable argument list for the arguments. πŸŽ€

int vsprintf_P (char * __s, const char * __fmt, va_list ap) [extern]

Variant of vsprintf() that uses a fmt string that resides in program memory. 🧠


✨ Author ✨

Generated automatically by Doxygen for AVR-LibC from the source code. πŸ€–


That's a wrap, bestie! This page came from AVR-LibC, version 2.2.1, and it's the avr_stdio(3avr) page β€” go forth and format/scan all the things πŸ’…πŸ¦‹

πŸ“¦ where this page comes from