Reputation: 50127
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:
#include
:s allowed. Not even a single one :-)Definition of correct answer:
putchar(char c)
function. Nothing more, nothing less :-)Upvotes: 15
Views: 14671
Reputation: 60933
void putchar(char c) {
extern long write(int, const char *, unsigned long);
(void) write(1, &c, 1);
}
Upvotes: 7
Reputation: 9169
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.
Upvotes: 0
Reputation: 272667
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.
Upvotes: 6
Reputation: 409384
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
.
Upvotes: 9