putchar(char)将字符写入标准输出,通常由stdio.h.提供.
我怎样写一个字符到标准输出,而不使用stdio.h或任何其他标准库文件(即:无 #include:■允许的)?
或者措辞不同,我如何putchar(char)用零#include语句实现自己的?
这就是我想要实现的目标:
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
澄清:
#include不允许.甚至没有一个:-)正确答案的定义:
putchar(char c)功能.没有更多,没有更少:-)在POSIX系统上,例如Linux或OSX,您可以使用write系统调用:
/*
#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;
}
Run Code Online (Sandbox Code Playgroud)
在Windows上有类似的功能.您可能需要打开控制台OpenFile然后再使用WriteFile.
没有与平台无关的方法.
当然,在任何指定的平台上,您可以通过重新实现/复制和粘贴stdio.h(以及依次依赖的任何实现)的实现来轻松实现这一点.但这不是便携式的.它也不会有用.
void putchar(char c) {
extern long write(int, const char *, unsigned long);
(void) write(1, &c, 1);
}
Run Code Online (Sandbox Code Playgroud)