我创建了一个名为 input.txt 的文本文件,内容很简单 - 3 后跟回车。
然后我用下面的源代码构建一个可执行文件 scanf_test.exe。
#include <stdio.h> /* scanf, printf */
/* input.txt file has contents "3" followed by carriage return */
int main(int argc, char* argv[]) {
int n;
printf("cmdline argc: %d\n", argc);
if(argc < 2)
return -1;
/* check we set cmd line ok */
printf("cmdline argv[1]: %s\n", argv[1]);
/* unfortunately freezes on this line in debugging mode (F5) or skips past in normal run mode (Ctrl F5)
Evben if I run from cmd line with eg scanf_test.exe <input.txt just returns printing nothing. */
scanf("%d\n", &n);
printf("n=%d", n);
return 0;
}
然后我像这样在命令行上运行:
C:\test\Debug>scanf_test.exe <input.txt
cmdline argc: 1
然后程序运行并返回但似乎没有从标准输入中获取数字 3?
C:\test\Debug>scanf_test.exe qqq
cmdline argc: 2
cmdline argv[1]: qqq
第二个示例传递了一个无意义的参数 - 但它至少识别了传递的参数。
我以为
<input.txt
将打开文件并输入内容。我做错了什么?
最佳答案
如果你只想从 input.txt 中读取一个数字,你可以在 scanf 之前使用 freopen("input.txt", "r", stdin),就像这样:
#include <stdio.h>
int main(int argc, char* argv[])
{
int n;
freopen("input.txt", "r", stdin);
scanf("%d", &n);
printf("n=%d", n);
return 0;
}
如果你想从命令行传递文件名:
#include <stdio.h>
int main(int argc, char* argv[])
{
int n;
if (argc != 2)
{
/*printf something here*/
return 0;
}
freopen(argv[1], "r", stdin);
scanf("%d", &n);
printf("n=%d", n);
return 0;
}
或者,如果你想像这样使用这个程序:
scanf_test < input.txt
你应该只写代码:
#include <stdio.h>
int main(int argc, char* argv[])
{
int n;
scanf("%d", &n);
printf("n=%d", n);
return 0;
}
它工作正常。
记住,不要在 scanf 格式字符串的末尾写 '\n'。 scanf 不是 printf!
关于c - 在 VS2008 中使用 scanf 读取重定向文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20594261/