从我先前的评论继续,存在使用read
和write
和使用像fgets
和printf
更高层次的功能,以stdin
阅读和写作之间的真正差别不大。主要区别在于,您不能依赖可变参数printf
提供的格式字符串以及read
,因此您有责任使用返回来知道实际读取了多少个字符。
下面是表示从stdin
与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!
最简单的方法可能一次只读一个字符如果你得到一个换行符,将字符附加到数组中。 –
如果你想从标准输入读取,你不需要事先指定数组的大小吗?我明白你的意思,但我不知道如何实施它。 – user3538161
使用'read/write'来完成输入/输出和使用'getchar/printf'确实没有什么区别。主要区别是您不喜欢格式化输出或可变打印功能。您必须按照您希望的输出方式将每个输出写入'stdout'来进行格式化。如果你仍然坚持让我知道。你可以像使用任何文件一样在'stdin'上使用read。你声明一个缓冲区(数组)并从'stdin'读入缓冲区。 'read'返回给你成功读取的字符数。 –