我可以使用printf
在控制台上轻松打印行。但是如何在没有std
库的情况下读取行?
答案 0 :(得分:1)
使用标准化方法,您的代码将保证可以跨不同平台移植。没有它,你必须为你想要定位的每个平台编写代码。
printf
和scanf
,std::cout
和std::cin
以及std::cerr
提供了从stdin / read到stderr的stdout / read的可移植方式。如果你想避免这种情况,你可能需要使用
HANDLE GetStdHandle(DWORD nStdHandle);
BOOL WINAPI WriteFile(
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
);
并使用
在POSIX兼容系统中ssize_t write(int fd, const void* buf, size_t count);
您知道,您永远不能将GetStdHandle
和WriteFile
移植到Unix,也不能将write
移植到Windows或其他系统(如Solaris)。即使你渴望编写包装函数,这也会比使用标准化库更加困难。
P.S。 DWORD nStdHandle
WinAPI参数分别与int fd
Unix API(前者requires -10
, -11
and -12
for stdin/stdout/stderr)不同,后者需要0,1和2。
即使你尝试做一些看似简单的事情,你最终也会做额外的工作。例如:
标准化:
#include<stdio.h>
printf("%d + %d = %d\n", a, b, a+b);
Unix的:
#include <unistd.h>
// <stdio.h> and <string.h> is still needed.
char buf[64];
snprintf(buf, sizeof(buf)/sizeof(char),
"%d + %d = %d\n", a, b, a+b);
ssize_t written =
write(1, buf, strlen(buf));
视窗:
#include <windows.h>
char buf[64];
snprintf(buf, sizeof(buf)/sizeof(char),
"%d + %d = %d\n", a, b, a+b);
HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwWritten;
BOOL failed = WriteFile(
hOutput, buf, strlen(buf), &dwWritten, NULL
);
实际上,如果您不想使用标准函数,则必须自己解析字符串。我使用snprintf
/ strlen
进行了简单说明,但肯定会有一些额外的工作。
答案 1 :(得分:0)