gpt4 book ai didi

c - 如何在c程序中重定向多个文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:58 25 4
gpt4 key购买 nike

如何在c程序中重定向多个文本文件?例如我有以下 C 代码:

//redirection.c
#include<stdio.h>
main()
{
int x,y;
scanf("%d",&x);
x=x*x;
printf("%d",x);

scanf("%d",&y);
y=x+y;
printf("%d",y);
}

编译这段代码后,我创建了两个文本文件 text1.txt,值为 8 和 text2.txt,值为 6。

当我使用命令行重定向(如 redirection<text1.txt)向该程序提供输入时,它提供输出 64 并且不等待接受另一个输入(并且程序退出),我想从 text2.txt 提供另一个输入。

有什么解决方案可以通过 text2.txt 为上述程序中的第二个 scanf 函数发送另一个输入吗?

最佳答案

像这样将输入作为重定向。

cat a b | ./a.out.

否则您可以使用命令行参数。

#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fp, *fp1;
if ( (fp=fopen(argv[1],"r")) == NULL ){
printf("file cannot be opened\n");
return 1;
}
if (( fp1=fopen(argv[2],"r")) == NULL ){
printf("file cannot be opened\n");
return 1;
}
int x,y;
fscanf(fp,"%d",&x);// If you having only the value in that file
x=x*x;
printf("%d\n",x);
fscanf(fp1,"%d",&y);// If you having only the value in that file
y=x+y;
printf("%d\n",y);

}

关于c - 如何在c程序中重定向多个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27873740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com