c - 在 VS2008 中使用 scanf 读取重定向文件

标签 c file-io stdin

我创建了一个名为 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/

相关文章:

c - 搜索并替换一个字符串,如下所示

c - mmap 与/开发/零

c - 指针的原因是指向第二种情况下字符串文字的最后一个字符

c - 为什么上传到微 Controller 的main函数中返回0?

java - 结果打印到控制台但不打印到文件

bash - 在程序开始时读取所有 stdin 会阻止在程序期间从 stdin 读取

java - 为什么这个文件无法删除?

unit-testing - 使用File类进行Grails Spock测试

ruby - 如何立即打印标准输出?

C:程序要求用户输入,即使输入文件作为参数给出