简体   繁体   English

将Cat命令与C代码一起使用

[英]Use Cat command with C code

I'm using the cat command for a school project. 我正在将cat命令用于学校项目。

What i need is to give a txt file as input to my code and then evaluate the output (saved in a txt file). 我需要给我的代码输入一个txt文件,然后评估输出(保存在txt文件中)。 So far i'm using this in my command line: 到目前为止,我在命令行中使用了它:

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

Where ./main is my C code. ./main是我的C代码。

The input_000.txt is structured like this: input_000.txt的结构如下:

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

I have a certain number of lines made of 5 characters (with spaces between them). 我的行数由5个字符组成(它们之间有空格)。

How do i get the content of each line in my C code? 如何在C代码中获取每一行的内容? I've been told so use standard input, but i've always used scanf only from keyboard input. 有人告诉我,请使用标准输入,但我始终只从键盘输入使用scanf

Does it still work in this case? 在这种情况下是否仍然有效?

And how should i save my output? 我应该如何保存输出? I usually use fwrite , but in this case is everything managed by the cat command 我通常使用fwrite ,但是在这种情况下,一切都由cat命令管理

That's how pipes works, it sets up so the output of the left-hand side of the pipe will be written to standard input for the right-hand side program. 这就是管道的工作方式,它进行了设置,因此管道左侧的输出将被写入右侧程序的标准输入。

In short if you can read input from stdin (like you do with plain scanf ) then you won't have to do any changes at all. 简而言之,如果您可以从stdin读取输入(就像使用普通scanf ),那么您根本就不需要进行任何更改。

Redirection works just about the same. 重定向的工作原理几乎相同。 Redirecting to a file ( > ) will make all writes to stdout go to the file. 重定向到文件( > )将使对stdout所有写操作都进入该文件。 Redirecting from a file ( < ) will make all reads from stdin come from the file. 从文件( < )重定向将使对stdin所有读取均来自该文件。

您可以使用getline(或scanf )读取stdin (fd = 0)并将其保存在C代码中的char*中……然后,您只需要编写stdout (fd = 1),然后>做好写在文件中的工作

What you need is something like this inside your function... 您需要的是函数内部的类似内容...

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'
}

If you don't want to use it...then you can give your main.c the input using < and saving the output > 如果您不想使用它...那么您可以使用<并保存输出>给main.c输入

./main.o < input.txt > output.txt ./main.o <input.txt> output.txt

(something like that, its not safer because the terminal could have the settings to use other type of charset... (这样的话,它并不安全,因为终端可以进行设置以使用其他类型的字符集...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM