Hi Guys,
I was trying to code in C for the following.
You are given with 2 files, file1.txt and file2.txt. The contents of the file contain INTERGER values. Add the contents of the file and write them to another file file3.txt.
My code is as follows
#include <stdio.h>
#include <stdlib.h>
int main()
{
static int data,data1,sum;
FILE *f1,*f2,*f3;
f1 = fopen("C:\\file1.txt","r");
f2 = fopen("C:\\file2.txt","r");
f3 = fopen("C:\\file3.txt","w");
while(( fscanf(f1,"%d",&data) != EOF ) || ( fscanf(f2,"%d",&data1) != EOF ))
{
if(data == EOF && data1 == EOF)
{
break;
}
else if(data == EOF)
{
sum += data1;
}
else if(data1 == EOF)
{
sum += data;
}
else
{
sum = sum + data + data1;
}
}
fprintf(f3,"%d\n",sum);
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
Contents of File1 --> 123
Contents of File2 --> 456
But after execution, when I open File3, it has the results as
702
Please help me with the code
P.S : I tried to add the contents without the while loop (i.e)., it can be applied for only one Input on each file and it worked fine. But I want to add the contents of the file that has multiple numbers in it.
Please help me