I have 8 files (file%d-%d.dat) each with 2 columns and 1000 rows:
File1-1 File1-2 File1-3 File1-4
x1a y1a x1b y1b x1c y1c x1d y1d
x2a y2a x2b y2b x2c y2c x2d y2d
x3a y3a x3b y3b x3c y3c x3d y3d
. . . .
. . . .
File2-1 File2-2 File2-3 File2-4
x1e y1e x1f y1f x1g y1g x1h y1h
x2e y2e x2f y2f x2g y2g x2h y2h
x3e y3e x3f y3f x3g y3g x3h y3h
. . . .
. . . .
I want to sum the second column of each file File%d-1 row by row and write the sum in a new file: Filesum1; same for File%d-2 and so on, i.e.,
Filesum1 Filesum2 and so on ..
x1a+x1e y1a+y1e x1b+x1f y1b+y1f .
x2a+x3e y2a+y2e x2b+x2f y2b+y2f .
. . . .
. . . . .
I created 4 new files:
#include <stdio.h>
int main(void)
{
int numfiles=4;
int numfileread=8;
int i,yy1, yy2, x0, x1;
FILE *files[numfiles];
FILE *f[numfileread];
for (int n = 0; n < 4; n++)
{
char filename[4];
sprintf(filename, "filesum%d.dat", n);
files[n] = fopen(filename, "w");
}
Then I've tried this, but it does not work correctly:
for (int n = 0; n < 4; n++)
{
yy1=0;
yy2=0;
for(int r=1;r<4;r++)
{
char file[8];
sprintf(file, "file%d-%d.dat", r, n);
f[i] = fopen(file, "r");
fscanf(f," %d %d",&x0,&x1);
yy1+=x0;
yy2+=x1;
fclose(f);
i++;
}
fprintf(files,"%d %d\n",yy1, yy2);
fclose(files);
}
If I had the same assignment, but for reading 50 files:
readFile1, readFile2, readFile3, ......., readFile50
How can I change the code?