我可以访问无键盘标准输入? [英] Can I access stdin without keyboard?

查看:89
本文介绍了我可以访问无键盘标准输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编译如下code用gcc

I have compiled the following code with gcc

int main() {

  int a = 0;

  fprintf( stdin, "%d", 123 );
  fscanf( stdin, "%d", &a );
  printf( "%d\n", a );

  return 0;
}

在我的意料,程序应执行直线(即程序一直没有停顿,等待用户输入)。但它仍然停下来,等待我的输入。

In my expectation, the program should executes straightly (i.e., the program never pause and wait for user input). But it still stop, and wait for my input.

我想知道,当我尝试写一些东西,以标准输入,以及如何修改此code发生什么,它可以直执行?

I want to know what happen when I try to write something to stdin and how to modify this code and it can execute straightly?

推荐答案

如果您打印出的fprintf中的返回值(标准输入你可以看到,函数调用失败。

If you print out the return value of fprintf(stdin you can see that the function call fails.

在外壳,你可以管的东西到标准输入的过程。

In the shell you can pipe something into the stdin of the process.

#include <stdio.h>

int main(void) {

  int a = 0, ret;

  printf("%d\n", ret = fprintf( stdin, "%d", 123 ));
  if (ret < 0) perror("fprintf");
  fscanf( stdin, "%d", &a );
  printf( "%d\n", a );

  return 0;
}


$ echo 123 | ./a.out
-1
fprintf: Bad file descriptor
123
$ 

这篇关于我可以访问无键盘标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆