So, I've already search this site to see if there was any question similar to mine and I came up empty-handed. Here's the setup. I used my program to write to a file and I stored the contents within a record (using arrays). The problem is that I can't seem to find a way to search the array of records for a specific code and manipulate whatever that is linked to that code. Here is a snippet of my program:
- Case 4 is where I print to the Stock.txt file and read the contents into variables.
- Case 5 is where I try to search the array using typedef for a code and printing what relates to the code.
I would like to know how to properly execute case 5.
case 4: ;
FILE *kfile ;
//opens the file called kfile found from the path below.
kfile= fopen("Stock.txt","w");
//prompts the programmer to enter a command to end the input of records.
printf("CTRL+Z' to end input\n");
printf("===========================================");
printf("\nUSE A SINGLE APACE BETWEEN EACH WORD/NUMBER");
printf("\n===========================================\n\n");
//while it is not the end of file, programmer still enters records of persons.
printf("Enter Code(MAX 3 letters), Item Name, Quantity, Price: \n");
scanf("%s %s %d %d", filecode, itemname, &quantity, &fileprice);
while (!feof(stdin) ){
fprintf(kfile,"%s\t%s \t%d\t%d\n", filecode, itemname, quantity, fileprice);
//prints to the file
printf("Enter Code(MAX 3 letters), Item Name, Quantity, Price: \n");
scanf("%s %s %d %d", filecode, itemname, &quantity, &fileprice);
}
fclose(kfile);
break;
case 5: ;
FILE *mfile;
if ((mfile = fopen("Stock.txt","r")) == NULL) {
perror("Error while opening file");
}else {
while (!feof(mfile)) {
fscanf(mfile, "%s\t%s \t%d\t%d", filecode, itemname, &quantity, &fileprice);
array[x].itemname1 = strdup(itemname);
array[x].code1 = strdup(filecode);
array[x].quantity1 = quantity;
array[x].price1 = fileprice;
}
fclose(mfile);
}
printf("Please enter Code: ");
scanf("%s", &codenew);
printf("\n");
printf("\nCode\tItem Name\tQuantity\tPrice\n");
for (x = 1; x <= 100; x++) {
if (strcmp(array[x].code1, codenew)==0) {
// print the record
printf("%s\t%s \t%d\t\t%d\n", array[x].code1,array[x].itemname1, array[x].quantity1,array[x].price1);
}
}
break;