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

How to redirect more than one text file in c programm

如何在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 函数发送另一个输入?

您还可以使用命令行参数:

#include <stdio.h>

#define BUFSIZE 1000

int main(int argc, char *argv[])
{
    FILE *fp1 = NULL, *fp2 = NULL;
    char buff1[BUFSIZE], buff2[BUFSIZE];

    fp1 = fopen(argv[1], "r");
    while (fgets(buff1, BUFSIZE - 1, fp1) != NULL)
    {
        printf("%s\n", buff1);
    }
    fclose(fp1);

    fp2 = fopen(argv[2], "r");
    while (fgets(buff2, BUFSIZE - 1, fp2) != NULL)
    {
        printf("%s\n", buff2);
    }
    fclose(fp2);
}

这是一个更简洁的版本:

#include <stdio.h>

#define BUFSIZE 1000
void print_content(char *file);
int main(int argc, char *argv[])
{
    print_content(argv[1]);
    print_content(argv[2]);
}

void print_content(char *file){
    char buff[BUFSIZE];
    FILE *fp = fopen(file, "r");

    while (fgets(buff, sizeof(buff), fp) != NULL)
    {
        printf("%s\n", buff);
    }
    fclose(fp);
}

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

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);

}