#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LINE_SIZE 100
struct products{
char uAd[5];
int uID;
int uSat;
int uAl;
int uStk;
};
void collectTheStk(struct products *p);
int main(){
FILE *f = fopen("file.txt","r");
if(f==NULL){
perror("file.txt");
exit(1);
}
struct products U[10];
size_t i;
//the total line inside of the file is 10 so going through the end
for (i = 0; i < 10; i ) {
char buf[LINE_SIZE];
if (fgets(buf, sizeof(buf), f) == NULL) {
break;
}
sscanf(buf, "%d %4s %d %d %d", &U[i].uID,
U[i].uAd, &U[i].uSat, &U[i].uAl, &U[i].uStk);
}
fclose(f);
collectTheStk(U);
return 0;
}
void collectTheStk(struct products *p){
FILE *fy = fopen("newfile.txt","w");
struct products newstk[10];
for(int i=0;i<10;i ){
for(int j=0;j<10;j ){
if(i==j) continue;
if((strcmp(p[i].uAd,p[j].uAd))==0){
//here i am taking the sum of stck number(and this is the point where i am struggling)
newstk[i].uStk = p[i].uStk p[j].uStk;
}
}
}
for(int n=0;n<10;n ){
fprintf(fy, "%d %s %d %d %d\n",p[n].uID, p[n].uAd, p[n].uSat, p[n].uAl, newstk[n].uStk);
}
fclose(fy);
printf("\nProccess is done check your new file\n");
}
This is inside of the file.
1 A 20 15 5
2 B 50 30 10
3 CD 60 40 2
7 O 77 35 20
4 EFG 3 1 100
1 A 20 15 25
5 HJ 150 100 8
6 KLMN 5 1 23
7 O 77 35 12
7 O 77 35 40
Inside the file the last column is the uStk(stock number). And the letters are uAd(name of the products). The problem is the letters A and O are repeating on different lines with different stock numbers. So what i want is after reading the file getting the sum of stock numbers and write them in the new file.
I was expecting to get the following new file.
1 A 20 15 30
2 B 50 30 10
3 CD 60 40 2
4 EFG 3 1 100
5 HJ 150 100 8
6 KLMN 5 1 23
7 O 77 35 72
This is the file what i am getting right now.
1 A 20 15 1968936544
2 B 50 30 6421668
3 CD 60 40 71
7 O 77 35 1345228322
4 EFG 3 1 14747728
1 A 20 15 -357094208
5 HJ 150 100 6421736
6 KLMN 5 1 6421824
7 O 77 35 -1604510652
7 O 77 35 -882665882
CodePudding user response:
newstk[i].uStk = newstk[i].uStk newstk[j].uStk;
is bad as newstk[j].uStk
never initialized nor assigned.
Zero out newstk[10]
with:
struct products newstk[10] = { { 0 } };
Likewise for struct products U[10];
.
struct products U[10] = { { 0 } };