[英]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
. putchar(char)
将一个字符写入标准输出,通常由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)? 如何在不使用
stdio.h
或任何其他标准库文件的情况下将字符写入标准输出(即: 不允许 #include
:s)?
Or phrased different, how do I implement my own putchar(char)
with zero #include
statements? 或者措辞不同,如何用零
#include
语句实现我自己的putchar(char)
?
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. #include
:s。 Not even a single one :-) Definition of correct answer: 正确答案的定义:
putchar(char c)
function. putchar(char c)
函数。 Nothing more, nothing less :-) On a POSIX system, such as Linux or OSX, you could use the write
system call: 在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;
}
On Windows there are similar functions. 在Windows上有类似的功能。 You probably have to open the console with
OpenFile
and then use WriteFile
. 您可能必须使用
OpenFile
打开控制台,然后使用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). 当然,在任何指定的平台上,您可以通过重新实现/复制和粘贴
stdio.h
的实现(以及依次依赖的任何东西)来实现这一点。 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. 由于提供完整的解决方案可能是非运动的,这是下一个最好的事情......这是Apple实施的源代码 - 这是开源的。
I think reducing this to a minimum case is an exercise for the OP. 我认为将此减少到最小的情况是OP的练习。 Apple have even kindly provided an XCode project file.
Apple甚至提供了一个XCode项目文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.