开发者

Using fputc() to write one byte

Given unsigned char *str, a UTF-8 encoded string, is it legal to write the first byte (not charact开发者_如何学编程er) with fputc((char)(*str), file);


Remove the cast to char. fputc takes the character to write as an int argument whose value is expected to be in the range of unsigned char, not char. Assuming (unsigned char)(char) acts as the identity operator on unsigned char values, there's no error in your code, but it's not guaranteed to especially for oddball systems without twos complement.


It's legal. fputc converts its int input to unsigned char, and that conversion can't do anything too unpleasant. It just takes the value modulo UCHAR_MAX+1.

If char is unsigned on your implementation, then converting from unsigned char to char doesn't affect the value.

If char is signed on your implementation, then converting a value greater than CHAR_MAX to char either has an implementation-defined result, or raises a signal (6.3.1.3/3). So while your code is legal, the possible behavior includes raising a signal that terminates the program, which might not be what you want.

In practice, you expect implementations to use 2's complement, and to convert to signed types in the "obvious" way, preserving the bit pattern.

Even if nothing else goes wrong, your terminal might not do anything sensible, if you write a strange byte to STDOUT.


No, you have to pass a FILE pointer as second parameter. This is the file handle you would like to write the character to, for example stdout.

fputc(*str, stdout);


Yes it is legal. fputc will just write a byte. The cast to signed/unsigned in this case will just stop the compiler moaning at you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜