C - Windows 重用以前程序的输出作为其他程序 cmd 重定向外壳的输入



我想这样做: 方案1 |程序2

我想使用第一个程序的输出作为程序 2 的输入(stdin(来进行一些计算。

现在这就是我在程序 2 中的内容

int main(int argc, char *argv[]) {
char userInput[100];
int num[100];
FILE *cmdLn = stdin;
if (argc > 2) {
fprintf(stderr, "Usage: %s [<file>]n", argv[0]);
exit(EXIT_FAILURE);
}
if (argc == 2) {
cmdLn = fopen(argv[1], "r");
if (!cmdLn) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
int numInput[100];
for (int i = 0; i < 100; i++) {
fscanf(cmdLn, "%d", &numInput[i]);
printf("%dn", 2*numInput[i]);
}

if (cmdLn != stdin) {
fclose(cmdLn);
}
exit(EXIT_SUCCESS);
}

程序 1 只是在每行创建几个数字。我想在程序 2 中使用这些数字将它们加倍并打印结果。

我在这里错过了什么?

我正在从 *文件中读取 fgets,该文件正在从 stdin 获取输入

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
char userInput[100];
int numInput[100];
FILE *file = stdin;
if (argc > 2) {
fprintf(stderr, "Usage: %s [<file>]n", argv[0]);
exit(EXIT_FAILURE);
}
if (argc == 2) {
file = fopen(argv[1], "r");
if (!file) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
int num[100];
while (fgets(userInput, sizeof(userInput), file))
{
num[i] = atoi(userInput);
printf("%dn", 2*num[i]);
i++;
}

if (file != stdin) {
fclose(file);
}
exit(EXIT_SUCCESS);
}

外壳重定向有效,但不完全是我想要的。 程序 1 给了我 10 个随机整数。 当我从程序 1 获得 10 个不同的数字并将其输出通过管道传输到程序 2 时,我得到新的 10 个随机值,而不是之前程序 1 的输出。 程序 2 应该计算这些(例如乘以 2(。

也许问题出在程序 1 上:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXNUM 1000
int main(int argc,char *argv[]) {
char *userInput[10];
time_t t;
int num = atoi(argv[1]);
srand(time(NULL));
for (int i = 0; i <= num; i++) {
printf("%dn", rand() % MAXNUM);
}
return 0;
}

问题是它会生成新的随机数。但是我想使用该程序的输出并将其乘以程序 2 与程序 2 相乘

我想我修复了它!哎呀! 是srand((导致了这个问题。取消评论解决了它。

最新更新