在 C 代码中使用 Cat 命令
Use Cat command with C code
我正在为一个学校项目使用 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 代码中每一行的内容?有人告诉我使用标准输入,但我一直只使用 scanf
键盘输入。
在这种情况下它仍然有效吗?
我应该如何保存我的输出?我通常使用 fwrite
,但在这种情况下,一切都由 cat
命令管理
这就是管道的工作原理,它设置为将管道左侧的输出写入右侧程序的标准输入。
简而言之,如果您可以从 stdin
读取输入(就像您使用普通 scanf
一样),那么您根本不需要做任何更改。
重定向的工作原理几乎相同。重定向到文件 (>
) 将使对 stdout
的所有写入都转到该文件。从文件 (<
) 重定向将使来自 stdin
的所有读取都来自该文件。
您可以使用 getline(或确实是 scanf
)读取 stdin
(fd = 0) 并将其保存在 C 代码中的 char*
中...然后您只需要在 stdout
(fd = 1) 中写入,您的 >
将完成写入文件
的工作
你需要的是在你的函数中有这样的东西...
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 > output.txt
(类似的东西,它不安全,因为终端可以设置使用其他类型的字符集...
我正在为一个学校项目使用 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 代码中每一行的内容?有人告诉我使用标准输入,但我一直只使用 scanf
键盘输入。
在这种情况下它仍然有效吗?
我应该如何保存我的输出?我通常使用 fwrite
,但在这种情况下,一切都由 cat
命令管理
这就是管道的工作原理,它设置为将管道左侧的输出写入右侧程序的标准输入。
简而言之,如果您可以从 stdin
读取输入(就像您使用普通 scanf
一样),那么您根本不需要做任何更改。
重定向的工作原理几乎相同。重定向到文件 (>
) 将使对 stdout
的所有写入都转到该文件。从文件 (<
) 重定向将使来自 stdin
的所有读取都来自该文件。
您可以使用 getline(或确实是 scanf
)读取 stdin
(fd = 0) 并将其保存在 C 代码中的 char*
中...然后您只需要在 stdout
(fd = 1) 中写入,您的 >
将完成写入文件
你需要的是在你的函数中有这样的东西...
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 > output.txt
(类似的东西,它不安全,因为终端可以设置使用其他类型的字符集...