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

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

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

Or are different formulated, how can 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; } 

Explanations:

  • Note: No #include : s is allowed. Not even a single one :-)
  • The solution should not be portable (built-in assembler, therefore, OK), but it must be compiled using gcc under MacOS X.

Determining the correct answer:

  • The working putchar(char c) function. Nothing more, nothing less :-)
+8
c macos
source share
4 answers
 void putchar(char c) { extern long write(int, const char *, unsigned long); (void) write(1, &c, 1); } 
+2
source share

There is no such platform-independent way to do this.

Of course, on any given platform, you can do this trivially by overriding / copying and pasting the implementation of stdio.h (and all that in turn relies on). But it will not be portable. And it will not be useful.

+6
source share

On a POSIX system such as Linux or OSX, you can 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, aka `STDOUT_FILENO` */ return 0; } 

Windows has similar features. You probably need to open the console with OpenFile and then use WriteFile .

+6
source share

Since providing complete solutions is probably unsportsmanlike, this is the next best thing ... which is the source code for Apple, the implementation - which is open source.

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

0
source share

All Articles