title: Best way to portably assign the result of fgetc() to a char in C
body: <p>Perhaps I'm overthinking this, as it seems like it should be a lot easier.  I want to take a value of type int, such as is returned by fgetc(), and record it in a char buffer if it is not an end-of-file code.  E.g.:</p>
  
  <pre><code>char buf;
  int c = fgetc(stdin);
  
  if (c &lt; 0) {
      /* handle end-of-file */
  } else {
      buf = (char) c;  /* not quite right */
  }
  </code></pre>
  
  <p>However, if the platform has signed default chars then the value returned by fgetc() may be outside the range of char, in which case casting or assigning it to (signed) char produces implementation-defined behavior (right?).  Surely, though, there is tons of code out there that does exactly the equivalent of the example.  Is it all relying on implementation-defined behavior and/or assuming 7-bit data?</p>
  
  <p>It looks to me like if I want to be certain that the behavior of my code is defined by C to be what I want, then I need to do something like this:</p>
  
  <pre><code>buf = (char) ((c &gt; CHAR_MAX) ? (c - (UCHAR_MAX + 1)) : c);
  </code></pre>
  
  <p>I think that produces defined, correct behavior whether default chars are signed or unsigned, and regardless even of the size of char.  Is that right?  And is it really needful to do that to ensure portability?</p>