题
是,即使可能?
让我们说,该代码有很多的scanf线。代替手动运行,并通过在调试时手添加值,是有可能为“喂”标准输入的数据,以便当scanf的开始读取,将读取所输入的数据,而不需要与终端进行交互。
解决方案
把测试线到一个文件中,并运行该程序是这样的:
myprogram < mytestlines.txt
不是黑客程序更好的以某种方式做自己。
当你调试代码,可以设置调试器到与该命令行运行它。
其他提示
为使你的程序多一点多才多艺,你可能要考虑重写你的程序中使用fscanf
,fprintf
等,使得它已经可以处理文件IO,而不是仅仅安慰IO;那么,当你想从stdin读取或写入stdout,你只是做线沿线的东西:
FILE *infile, *outfile;
if (use_console) {
infile = stdin;
outfile = stdout;
} else {
infile = fopen("intest.txt", "r");
outfile = fopen("output.txt", "w");
}
fscanf(infile, "%d", &x);
fprintf(outfile, "2*x is %d", 2*x);
由于多久方案只能处理标准输入/输出和不允许的文件?特别是,如果你最终在外壳脚本中使用你的程序,也可以是更明确的,以指定在命令行上输入和输出。
int fd[2];
pipe(fd);
close(0); // 0:stdin
dup(fd[0], 0); // make read pipe be stdin
close(fd[0]);
fd[0] = 0;
write(fd[1], "some text", 9); // write "some text" to stdin
不隶属于 StackOverflow