使用标准化方法,您的代码将保证可跨不同平台移植。没有它,你必须为你想要定位的每个平台编写代码。
printf 和 scanf、std::cout 和 std::cin 和 std::cerr 提供了可移植的方式来写入标准输出/从标准输入读取/写入标准错误。如果你想避免这种情况,你可能需要在 Windows 中写入标准输出
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)。即使您急于编写包装函数,这也比使用标准化库更痛苦。
附: 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 来简化说明,但肯定是一些额外的工作。