从没有STD的控制台读取线路

时间:2017-09-24 09:14:54

标签: c++ io

我可以使用printf在控制台上轻松打印行。但是如何在没有std库的情况下读取行?

2 个答案:

答案 0 :(得分:1)

使用标准化方法,您的代码将保证可以跨不同平台移植。没有它,你必须为你想要定位的每个平台编写代码。

printfscanfstd::coutstd::cin以及std::cerr提供了从stdin / read到stderr的stdout / read的可移植方式。如果你想避免这种情况,你可能需要使用

写入Windows中的stdout
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);

您知道,您永远不能将GetStdHandleWriteFile移植到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)

标准库提供了保证跨平台的方法,因此建议使用它。

如果不这样做,则需要编写针对平台的特定代码。

例如,如果您想要定位Linux,那么您将使用read()

  

从文件描述符中读取