从没有STD的控制台中读取行

Read line from console without STD

本文关键字:读取 控制台 STD      更新时间:2023-10-16

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

使用标准化方法,您的代码将被保证在不同平台上可移植。没有这些,您必须为要定位的每个平台编写代码。

printfscanfstd::coutstd::cin and std::cerr提供了可移植的方法来写入stdout/to stdin/read/read to stdin/will to stderr。如果要避免这种情况,则可能必须在Windows中写入

的to 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不同,前者分别需要 -10-11-12,分别用于stdin/stdout/stderr,而后者则需要0、1和2。

。 。

即使您尝试做一些看似简单的事情,您最终还是做额外的工作。例如:

标准化:

#include<stdio.h>
printf("%d + %d = %dn", 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 = %dn", a, b, a+b);
ssize_t written =
  write(1, buf, strlen(buf));

Windows:

#include <windows.h>
char buf[64];
snprintf(buf, sizeof(buf)/sizeof(char),
    "%d + %d = %dn", a, b, a+b);
HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwWritten;
BOOL failed = WriteFile(
    hOutput, buf, strlen(buf), &dwWritten, NULL
);

实际上,如果您不想使用标准功能,则必须自己解析字符串。我使用 snprintf/strlen来轻松插图,但肯定是一些额外的工作。

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

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

例如,如果要定位Linux,则使用read()

从文件描述符读取