[英]How to redirect more than one text file in c programm
How to redirect more than one text file in c program? 如何在C程序中重定向多个文本文件? For example I have the following C code: 例如,我有以下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);
}
After compiling this code I created two text files text1.txt having the value 8 and text2.txt having the value 6. 编译此代码后,我创建了两个文本文件text1.txt,它们的值分别为8和text2.txt,它们的值是6。
When I give input to this program using command line redirection (as redirection<text1.txt
), it gives output 64 and does not wait to take another input (and program exits) which I want to give another input from text2.txt. 当我使用命令行重定向为该程序提供输入时(如redirection<text1.txt
),它给出输出64,并且不等待接受另一个要从text2.txt提供另一个输入的输入(程序退出)。
Is there any solution how can I send another input via text2.txt for second scanf function in the above program? 有什么解决方案,如何在上述程序中通过text2.txt为第二个scanf函数发送另一个输入?
While giving the input as redirection as like this. 像这样将输入作为重定向。
cat a b | ./a.out.
Or else you can use the command line arguments. 否则,您可以使用命令行参数。
#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);
}
you can also use command line arguments: 您还可以使用命令行参数:
#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);
}
here is a more cleaned up version: 这是一个更清理的版本:
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.