'How to take data from one file and put it into another in C [closed]
Here is the code
#include <stdio.h>
int main(void)
{
int a, b,sum;
FILE *in;
FILE *out;
in=fopen("numbers.txt","r");
out=fopen("sums.txt","w");
if(in== || out==NUll){
printf("File open failed.\n");
return 0;
}
else{
fscanf(in,"%d %d",&a,&b);
sum=a+b;
fprintf(out,"%d %d %d",a,b,sum);
fclose(in);
fclose(out);
}
return 0;
}
numbers.txt is in the form
a b
a b
etc..
so i am trying to take a and b and then inside sums.txt print out a, b and then the sum of the two. thanks.
Solution 1:[1]
Suggested changes:
#include <stdio.h>
int main(void)
{
int a, b,sum;
FILE *in;
FILE *out;
in=fopen("numbers.txt","r");
out=fopen("sums.txt","w");
if((!in) || !(out)){
perror("File open failed.\n");
return 1;
}
else{
int n = fscanf(in,"%d %d",&a,&b);
if (n != 2) {
printf("File read error!\n");
} else {
sum=a+b;
fprintf(out,"%d %d %d",a,b,sum);
}
fclose(in);
fclose(out);
}
return 0;
}
- perror() can help give you a more meaningful error message
- As others have pointed out,
if(in== || out==NUll)is incorrect. - It's important to check the return value from fscanf() to ensure you've read the expected data correctly.
'Hope that helps!
Solution 2:[2]
Put the code that reads and writes in a loop.
else{
while(fscanf(in,"%d %d",&a,&b) == 2) {
sum=a+b;
fprintf(out,"%d %d %d\n",a,b,sum);
}
fclose(in);
fclose(out);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Barmar |
