<stdio.h>: Standard IO facilities

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

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

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 == '\n') uart_putchar('\r');
  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 will also save some execution time.

Types, Constants, Globals

#define FILE	struct __file
#define stdin	(__iob[0])
#define stdout	(__iob[1])
#define stderr	(__iob[2])
#define EOF	-1

FILE

FILE is the opaque structure that is passed around between the various standard IO functions.

stdin, stdout, stderr

stdin (type is FILE*)
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.

stdout (type is FILE*)
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.

stderr (type is FILE*)
Stream destined for error output. Unless specifically assigned, 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).

EOF

EOF declares the value that is returned by various standard IO functions in case of an error. Since the AVR platform (currently) doesn't contain an abstraction for actual files, its origin as “end of file” is somewhat meaningless here.

Stream Setup

#define fdev_setup_stream(stream,pt,get,rwflag)
#define FDEV_SETUP_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_set_udata(stream, u)	((stream)->udata = u)
#define fdev_get_udata(stream)		((stream)->udata)

fdev_setup_stream, FDEV_SETUP_STREAM

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 is valid for stdio operations similar to one that has been obtained dynamically from fdevopen(). The buffer to setup 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: Running stdio without malloc().
FDEV_SETUP_STREAM acts similar to fdev_setup_stream(), but it is to be used as the initializer of a variable of type FILE.

_FDEV_SETUP_READ, _FDEV_SETUP_WRITE, _FDEV_SETUP_RW

fdev_setup_stream() with read / write / read+write intent.

_FDEV_EOF, _FDEV_ERR

Return code for an end-of-file or error condition during device read.

To be used in the get function of fdevopen().

fdev_get_udata, fdev_set_udata

fdev_get_udata retrieves a pointer to user defined data from a FILE stream object.

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

The user data can be useful for tracking state in the put and get functions supplied to the fdevopen() function.

Open, Close, Status

#include <stdio.h>

FILE * fdevopen (int(*put)(char, FILE *), int(*get)(FILE *));
#define fdev_close()
int    fclose (FILE *stream);
int      feof (FILE *stream);
int    ferror (FILE *stream);
void clearerr (FILE *stream);

fdevopen

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.

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.

fdev_close

This macro frees up any library resources that might be associated with stream. It should be called if stream is no longer needed, right before the 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.)

fclose

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

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

It currently always returns 0 (for success).

feof

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

ferror

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

clearerr

Clear the error and end-of-file flags of stream.

Stream Input

#define getchar()	fgetc(stdin)
#define getc(stream)	fgetc(stream)
int    fgetc (FILE *stream);
int   ungetc (int c, FILE *stream);
char * fgets (char *buf, int size, FILE *stream);
char *  gets (char *buf);
size_t fread (void *p, size_t s, size_t e, FILE *stream);

getchar

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

getc

The macro getc used to be a “fast” macro implementation with a functionality identical to fgetc(). For space constraints, in avr-libc, it is just an alias for fgetc.

fgetc

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.

ungetc

The ungetc() function pushes the character c (converted to an unsigned char) back onto the input stream pointed to by stream. The pushed-back character will be returned by a subsequent read on the stream.

Currently, only a single character can be pushed back onto the stream.

The ungetc() function returns the character pushed back after the conversion, or EOF if the operation fails. If the value of the argument c character equals EOF, the operation will fail and the stream will remain unchanged.

fgets

Read at most size-1 bytes from stream, until a newline character was encountered, and store the characters in the buffer pointed to by buf. 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.

gets

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.
Deprecation due to buffer overflow risk
This function should be replaced by gets_s, and is no more C standard.

fread

Read e objects, s bytes each, from stream, to the buffer pointed to by p.

Returns the number of objects successfully read, i. e. e unless an input error occured or end-of-file was encountered. feof() or ferror() must be used to distinguish between these two conditions.

Formatted Input

#include <stdio.h>

int   scanf  (		    const char *fmt, ...);
int   scanf_P(		    const char *fmt, ...);
int  fscanf  (FILE *stream, const char *fmt, ...);
int  fscanf_P(FILE *stream, const char *fmt, ...);
int  sscanf  (const char*s, const char *fmt, ...);
int  sscanf_P(const char*s, const char *fmt, ...);
int  vscanf  (		    const char *fmt, va_list ap);
int vfscanf  (FILE *stream, const char *fmt, va_list ap);
int vfscanf_P(FILE *stream, const char *fmt, va_list ap);

scanf, scanf_P

The function scanf performs formatted input from stream stdin.

See vfscanf() for details.

scanf_P is a variant of scanf() where fmt resides in program memory.

fscanf, fscanf_P

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

See vfscanf() for details.

fscanf_P is a variant of fscanf() using a fmt string in program memory.

sscanf, sscanf_P

The function sscanf performs formatted input, reading the input data from the buffer pointed to by buf.

See vfscanf() for details.

sscanf_P is a variant of sscanf() using a fmt string in program memory.

vscanf

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

See vfscanf() for details.

vfscanf, vfscanf_P

Formatted input. This function is the heart of the scanf family 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 %:

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:

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. Discarded conversion results (with * option) are not(?) counted.

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

vfscanf_P is a variant of vfscanf() using a fmt string in program memory.

Stream Output

#include <stdio.h>

#define putchar(c)	fputc(c, stdout)
#define putc(c, stream)	fputc(c,stream)
int  puts  (const char *s);
int  puts_P(const char *s);
int fputc  (int c,	   FILE *stream);
int fputs  (const char *s, FILE *stream);
int fputs_P(const char *s, FILE *stream);
size_t fwrite (const void *p, size_t s, size_t e, FILE *stream);
int fflush (FILE *stream);

putchar

The macro putchar sends character c to stdout.

putc

The macro putc used to be a “fast” macro implementation with a functionality identical to fputc(). For space constraints, in avr-libc, it is just an alias for fputc.

puts, puts_P

Write the string pointed to by s, and a trailing newline character, to stdout.

puts_P is a variant of puts() where s resides in program memory.

fputc

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.

fputs, fputs_P

Write the string pointed to by s to stream stream.

Returns 0 on success and EOF on error.

fputs_P is a variant of fputs() where s resides in program memory.

fwrite

Write e objects, s bytes each, to stream. The first byte of the first object is referenced by p.

Returns the number of objects successfully written, i. e. e unless an output error occured.

fflush

Flush stream.

This is a null operation provided for source-code compatibility only, as the standard IO implementation currently does not perform any buffering.

Formatted Output

#include <stdio.h>

int    printf  (		const char *fmt, ...);
int    printf_P(		const char *fmt, ...);
int   fprintf  (FILE *stream,	const char *fmt, ...);
int   fprintf_P(FILE *stream,	const char *fmt, ...);
int   sprintf  (char *buf,	const char *fmt, ...);
int   sprintf_P(char *buf,	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   vprintf  (		const char *fmt, va_list ap);
int  vfprintf  (FILE *stream,	const char *fmt, va_list ap);
int  vfprintf_P(FILE *stream,	const char *fmt, va_list ap);
int  vsprintf  (char *buf,	const char *fmt, va_list ap);
int  vsprintf_P(char *buf,	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);

printf, printf_P

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

printf_P is a variant of printf() that uses a fmt string that resides in program memory.

fprintf, fprintf_P

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

fprintf_P is a variant of fprintf() that uses a fmt string that resides in program memory.

sprintf, sprintf_P

Variant of printf() that sends the formatted characters to string buf.

sprintf_P is a variant of sprintf() that uses a fmt string that resides in program memory.

snprintf, snprintf_P

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.

snprintf_P is a variant of snprintf() that uses a fmt string that resides in program memory.

vprintf

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

See vfprintf() for details.

vfprintf, vfprintf_P

vfprintf is the central facility of the printf family of functions. It outputs values to stream under control of a format string passed in fmt. The actual values to print are passed as a variable argument list ap.

vfprintf returns the number of characters written to stream, or EOF in case of an error. Currently, this will only happen if stream has not been opened with write intent.

The format string is composed of zero or more directives: ordinary characters (not %), which are 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) with the conversion specifier. After the %, the following appear in sequence:

The conversion specifiers and their meanings are: 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.

Since the full implementation of all the mentioned features becomes fairly large, 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). 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:
Notes:
vfprintf_P is a variant of vfprintf() that uses a fmt string that resides in program memory.

vsprintf, vsprintf_P

Like sprintf() but takes a variable argument list for the arguments.

vsprintf_P is a variant of vsprintf() that uses a fmt string that resides in program memory.

vsnprintf, vsnprintf_P

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.

vsnprintf_P is a variant of vsnprintf() that uses a fmt string that resides in program memory.