从没有STD的控制台中读取行
Read line from console without STD
i可以使用printf
轻松在控制台上打印行。但是如何在没有std
库的情况下读取行?
使用标准化方法,您的代码将被保证在不同平台上可移植。没有这些,您必须为要定位的每个平台编写代码。
printf
和 scanf
, std::cout
和 std::cin
and std::cerr
提供了可移植的方法来写入stdout/to stdin/read/read to stdin/will to stderr。如果要避免这种情况,则可能必须在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)。即使您渴望编写包装纸功能,这将比使用标准化库更多。
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()
:
从文件描述符读取
相关文章:
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 从文件读取并通过矢量输出到控制台
- 反转从控制台读取的文本
- 控制台未正确读取输入字符串
- 如何读取windows服务启动的控制台应用程序的输出
- 如何使用 cin 将整数从控制台读取到向量中
- 如何从 c++ 控制台读取未知行数(允许空行)上的输入
- 硬编码字符串与强制转换为 PUCHAR 并打印到控制台时从控制台读取的字符串的结果不同
- 如何从控制台启动可执行文件并使用Qt读取输出
- C++ 从控制台读取整数数组
- 从控制台输出读取 C++
- 指向C 中的结构 - 从控制台读取
- 控制台将继续关闭,而不是读取 if 语句中的字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 在Qt控制台应用程序中读取和写入QProcess
- 如何从文件中一次读取一个输入,类似于在c++中使用cin/scanf从控制台读取输入
- 执行带有参数的 .bat 文件并以 C++ 格式读取控制台输出
- 从控制台读取字符
- 使用RInside读取R控制台
- 读取控制台调色板的 RGB 值