Alif Khair Alif Khair - 3 months ago 8
C Question

C programming Displaying txt FILE in compiler

The code works like a charm at the moment. But, the last 2 lines of output are identical as you can see here.

What is the problem here?

The datas came from a txt file that was build earlier.

1 CADBURY 999 1.900000
2 PEPSI 999 2.500000
3 IPHONE 976 2500.000000
4 SPIRULINA 100 50.000000
2 PAIPSI 100 0.900000
10 BLACKMORE 98 30.000000
17 TROPICANA 13 1.500000
17 TROPICANA 13 1.500000


Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>

int addProduct();

struct product {
int quantity, reorder, i, id;
char name[20];
float price;
};

int main() {
FILE *fp;
int i = 0;
struct product a;

system("cls");

char checker;
int counter;

do {
fp = fopen("addproduct.txt", "a+t");
system("cls");

printf("Enter product ID : ");
scanf(" %d", &a.id);

printf("Enter product name : ");
scanf(" %s", a.name);

printf("Enter product quantity : ");
scanf(" %d", &a.quantity);

printf("Enter product price : ");
scanf(" %f", &a.price);

fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
printf("Record saved!\n\n");

fclose(fp);

printf("Do you want to enter new product? Y / N : ");

scanf(" %c", &checker);
checker = toupper(checker);

i++;

system("cls");
} while(checker == 'Y');

if (checker == 'N') {
fp = fopen("addproduct.txt", "r");

while (!feof(fp)) {
fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price);
printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}
fclose(fp);
}
return(0);
}

Answer

while (!feof(fp)) does not work as expected: feof(fp) only becomes true after input has failed. During the last iteration, fscanf() fails, but you do not check its return value and the values from the previous iterations are used by the last printf().

You should instead write:

while (fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price) == 4) {
    printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}