stdin
继续我之前的评论,阅读和写作与使用read
andwrite
和使用更高级别的函数(如fgets
and )之间几乎没有区别printf
。主要区别是您不能依赖 variadic 提供的格式字符串printf
,而使用read
,您负责使用返回来了解实际读取了多少个字符。
下面是一个简短的示例,显示了从stdin
with读取输入read
然后用write
(注意:您应该添加额外的检查,例如检查读取的字符数是否小于缓冲区的大小以了解是否更多字符仍有待阅读等...)您始终可以将大部分提示read
放入函数中以简化重复使用。
使用write
,请记住,您写入内容的顺序stdout
是格式字符串。因此,只需进行合乎逻辑的调用即可write
完成您想要的格式。虽然您可以自由使用STDIN_FILENO
定义,但您也可以简单地使用0 - stdin
,1 - stdout
和2 - stderr
:
#include <unistd.h>
#define MAXC 256
int main (void) {
char buf[MAXC] = {0};
ssize_t nchr = 0;
/* write the prompt to stdout requesting input */
write (1, "\n enter text : ", sizeof ("\n enter text : "));
/* read up to MAXC characters from stdin */
if ((nchr = read (0, buf, MAXC)) == -1) {
write (2, "error: read failure.\n", sizeof ("error: read failure.\n"));
return 1;
}
/* test if additional characters remain unread in stdin */
if (nchr == MAXC && buf[nchr - 1] != '\n')
write (2, "warning: additional chars remain unread.\n",
sizeof ("warning: additional chars remain unread.\n"));
/* write the contents of buf to stdout */
write (1, "\n text entered: ", sizeof ("\n text entered: "));
write (1, buf, nchr-1);
write (1, "\n\n", sizeof ("\n\n"));
return 0;
}
编译
gcc -Wall -Wextra -o bin/read_write_stdin read_write_stdin.c
输出
$ ./bin/read_write_stdin
enter text : The quick brown fox jumps over the lazy dog!
text entered: The quick brown fox jumps over the lazy dog!