在linux上执行C语言输入文件

时间:2017-11-22 07:36:25

标签: c linux bash shell

我不明白

之间有多么不同

一个。 ./target <input
  湾./target <$(cat input)
  C。 ./target $(<input)

./target是C程序,输入是文件或有效负载

我想知道他们有什么不同,还有更多的技巧或方法吗?

1 个答案:

答案 0 :(得分:2)

三种符号中有两种是Bash特有的;这三个都是贝壳符号。运行的程序需要以完全不同的方式处理数据。

  1. ./target <input - input redirection):目标程序需要读取标准输入才能获取信息。

    #include <stdio.h>
    
    int main(void)
    {
        int c;
        while ((c = getchar()) != EOF)
            putchar(c);
        return 0;
    }
    
  2. ./target <$(cat input) - process substitution):目标程序需要打开命令行参数中指定的文件名以获取信息。

    #include <stdio.h>
    
    int main(int argc, char **argv)
    {
        if (argc != 2)
        {
            fprintf(stderr, "Usage: %s file\n", argv[0]);
            return 1;
        }
        FILE *fp = fopen(argv[1], "r");
        if (fp == 0)
        {
            fprintf(stderr, "%s: failed to open file '%s' for reading\n",
                    argv[0], argv[1]);
            return 1;
        }
    
        int c;
        while ((c = getc(fp)) != EOF)
            putchar(c);
    
        fclose(fp);
        return 0;
    }
    
  3. ./target $(<input) - command substitution):目标程序将文件内容拆分为单词作为程序的参数,每个参数一个单词。

    #include <stdio.h>
    
    int main(int argc, char **argv)
    {
        int count = 0;
        for (int i = 0; i < argc; i++)
        {
           count += printf(" %s", argv[i]);
           if (count > 70)
               putchar('\n'), count = 0;
        }
        return 0;
    }
    
  4. 因此,所需的处理是完全不同的。