I think that we can guarantee that the call to foo,
int foo (FILE * f, int i)
{
return fprintf(f, "%i", i);
}
will never produce an an encoding error if we can guarantee that i is not a trap representation (N2176, Representation of Types: General) because the characters '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', and '9' are found in the basic execution character set (N2176, Environmental Considerations: Character Sets), and these are all that are needed to represent the decimal form of any integral value that can be represented by an int. Also, the number of characters needed for the decimal representation of an int is guaranteed to be less than INT_MAX (so the return value of fprintf can always store the number of characters produced by the conversion).
So, the question reduces to:
How do we guarantee that an int does not store a trap representation?
(Or is it more complex?)
It's more complex.
This section has been added in response to the answers and comments (regarding orientation ) thus far (2022-02-18).
I think that we can guarantee that calls to fputi and / or fwputi,
#include <stdio.h>
#include <wchar.h>
int fputi ( int i , FILE * f )
{
return fwide ( f , 0 ) <= 0
? fprintf ( f , "%i" , i )
: fwprintf ( f , L"%i" , i ) ;
}
// The only differences between fputi and fwputi should be:
// - their names and
// - the "<" or "<=" signs.
int fwputi ( int i , FILE * f )
{
return fwide ( f , 0 ) < 0
? fprintf ( f , "%i" , i )
: fwprintf ( f , L"%i" , i ) ;
}
will never produce an an encoding error if we can guarantee that i is not a trap representation (N2176, Representation of Types: General) because the characters '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', and '9' are found in the basic execution character set (N2176, Environmental Considerations: Character Sets), and these are all that are needed to represent the decimal form of any integral value that can be represented by an int. Also, the number of characters needed for the decimal representation of an int is guaranteed to be less than INT_MAX (so the return value of fprintf or fwprintf can always store the number of characters produced by the conversion).
So, the question reduces to:
How do we guarantee that an i does not store a trap representation? Or, how do we modify fputi and fwputi so that they behave portably (i.e., consistently for all implementations that adhere to the Standard)? Maybe insert before the return statements:
// C-LIKE PSEUDO CODE
if ( isTrapRepresentation ( i ) ) exit ( EXIT_FAILURE ) ;