代码之家  ›  专栏  ›  技术社区  ›  Mattia Surricchio

使用带有C代码的cat命令

  •  0
  • Mattia Surricchio  · 技术社区  · 6 年前

    我正在使用cat命令进行学校项目。

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

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

    其中,/main是我的C代码。

    输入_000.txt的结构如下:

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

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

    如何获取C代码中每行的内容?我被告知使用标准输入,但我一直使用 scanf 仅从键盘输入。

    在这种情况下它还能工作吗?

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

    3 回复  |  直到 6 年前
        1
  •  2
  •   Some programmer dude    6 年前

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

    简而言之,如果您可以从 stdin (就像你对待平原一样 scanf )那么你就不需要做任何改变了。

    重定向的工作原理大致相同。重定向到文件( > )将所有写入 stdout 转到文件。从文件重定向( < )将从中读取所有内容 斯坦丁 从档案里出来。

        2
  •  1
  •   Killian G.    6 年前

    您可以使用getline(或 scanf 确实)阅读 stdin (fd=0)并将其保存在 char* 在您的C代码中…那么你只需要在 stdout (fd=1)和 > 会把你的文件写进去的

        3
  •  1
  •   maryf    6 年前

    你需要的是在你的函数里面有这样的东西…

    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.c提供输入,并保存输出>

    /main.o<input.txt>输出.txt

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