简体   繁体   中英

How do I write a character to standard output in C without using stdio.h or any other library header files?

putchar(char) writes a character to standard output and is normally provided by stdio.h .

How do I write a character to standard output without using stdio.h or any other standard library file (that is: no #include :s allowed)?

Or phrased different, how do I implement my own putchar(char) with zero #include statements?

This is what I want to achieve:

/* NOTE: No #include:s allowed! :-) */ 

void putchar(char c) {
  /*
   * Correct answer to this question == Code that implements putchar(char).
   * Please note: no #include:s allowed. Not even a single one :-)
   */
}

int main() {
  putchar('H');
  putchar('i');
  putchar('!');
  putchar('\n');
  return 0;
}

Clarifications:

  • Please note: No #include :s allowed. Not even a single one :-)
  • The solution does not have to be portable (inline assembler is hence OK), but it must compile with gcc under MacOS X.

Definition of correct answer:

  • A working putchar(char c) function. Nothing more, nothing less :-)

On a POSIX system, such as Linux or OSX, you could use the write system call:

/*
#include <unistd.h>
#include <string.h>
*/

int main(int argc, char *argv[])
{
    char str[] = "Hello world\n";

    /* Possible warnings will be encountered here, about implicit declaration
     * of `write` and `strlen`
     */
    write(1, str, strlen(str));
    /* `1` is the standard output file descriptor, a.k.a. `STDOUT_FILENO` */

    return 0;
}

On Windows there are similar functions. You probably have to open the console with OpenFile and then use WriteFile .

There is no platform-independent way of doing this.

Of course, on any specified platform, you can trivially achieve this by reimplementing/copy-and-pasting the implementation of stdio.h (and anything that this in turn relies on). But this won't be portable. Nor will it be useful.

void putchar(char c) {
  extern long write(int, const char *, unsigned long);
  (void) write(1, &c, 1);
}

Since providing a full solutions is probably unsporting, this is the next best thing... which is the source-code for Apple's implementation - which is open source.

I think reducing this to a minimum case is an exercise for the OP. Apple have even kindly provided an XCode project file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM