Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

macos

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 :-)
like image 302
knorv Avatar asked Jan 12 '13 17:01

knorv


1 Answers

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.

like image 166
Some programmer dude Avatar answered Sep 25 '22 08:09

Some programmer dude