【问题标题】:Use Cat command with C code在 C 代码中使用 Cat 命令
【发布时间】:2018-07-24 11:55:51
【问题描述】:

我正在将 cat 命令用于学校项目。

我需要提供一个 txt 文件作为我的代码的输入,然后评估输出(保存在 txt 文件中)。 到目前为止,我在命令行中使用它:

cat input_000.txt | ./main > my_output.txt

./main 是我的 C 代码。

input_000.txt 的结构如下:

0 a a R 3
1 a b L 4
4 c b R 1
ecc...

我有一定数量的由 5 个字符组成的行(它们之间有空格)。

如何获取 C 代码中每一行的内容?有人告诉我要使用标准输入,但我一直使用scanfonly 来自键盘输入。

在这种情况下它仍然有效吗?

我应该如何保存我的输出?我通常使用fwrite,但在这种情况下,一切都由cat 命令管理

【问题讨论】:

  • read from pipe line by line in c 的可能重复项。
  • "但我一直使用scanfonly 来自键盘输入。"在那种情况下,stdin 正在从您的键盘读取。但它仍然是stdin
  • cat 应该完全不相关,你的第一个 sn-p 是经典的useless use of cat。 (正确命令:./main <input_000.txt >my_output.txt
  • @FelixPalmen 为什么没用?我正在报告我们教授的命令。输入 txt 进入 C 代码(充当过滤器)并将结果打印到第二个 txt 中。 link 这里有一个类似的例子 'cat file1 file2 file3 |排序 > 文件 4'
  • @MattiaSurricchio 好,请点击我的链接。简而言之,shell 可以将文件提供给stdin,这就是输入重定向的用途。 cat 用于连接,如果您只读取一个文件,则大多数情况下它是无用的 - 并且会花费您另一个进程。

标签: c linux cat


【解决方案1】:

这就是管道的工作原理,它设置了管道左侧的输出将写入右侧程序的标准输入。

简而言之,如果您可以读取来自 stdin 的输入(就像使用普通的 scanf 一样),那么您根本不需要做任何更改。

重定向的工作原理几乎相同。重定向到文件 (>) 将使所有对 stdout 的写入都转到该文件。从文件 (<) 重定向将使来自 stdin 的所有读取都来自该文件。

【讨论】:

  • 为了保存输出,我可以同时使用 fwrite(stdout) 和 printf?
  • @MattiaSurricchio 您的意思是要保存来自printf 的输出(以及写入stdout 的其他函数)来写入文件吗?那我建议你使用the tee command而不是重定向你的输出。
【解决方案2】:

您可以使用getline(或scanf确实)读取stdin(fd = 0)并将其保存在您的C代码中的char*中......然后您只需要写入@987654324 @ (fd = 1) 和您的 > 将完成写入文件的工作

【讨论】:

    【解决方案3】:

    你需要的是在你的函数中这样的东西......

    FILE *input = fopen("input.txt","rw"); //rw (read-write)
    FILE *output= fopen("output.txt","rw"); //rw (read-write)
    char inputArray[500];
    char outputArray[500];
    
    while(fscanf(input,"%s", inputArray) != EOF){
          //read the line and save in 'inputArray'
          //you can also use %c to find each caracter, in your case I think it's better...you can //save each caracter in a array position, or something like that
    }
    
    while(number of lines you need or the number of lines from your input file){
          fprintf(output,"%s\n",output); //this will write the string saved in 'outputArray'
    }
    

    如果您不想使用它...那么您可以使用

    ./main.o output.txt

    (类似的东西,它并不安全,因为终端可以设置使用其他类型的字符集...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 2021-07-14
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多