0

I am writing a program which will update the price of information which is coming from a text file and then display to stdout.

The issue I am having is that I will try to read information from the existing text file with information into the structure. Then edit the price variable.

I am unable to write, append, or do any of the + feature of this file I can only read it.

The change in price will display to standard output fine but it won't change the price value in the text file existing. I attached the structure and the function I'll be using to change the variable.

void printPrice() {

    double chg;
    puts("=====================================");
    printf("please enter a change of a value using precentage ");
    scanf("%lf", & chg);
    printf("Prices changed\n");
    printf("writing to book file completed\n");
    puts("=====================================\n");
    FILE * file = fopen("books.txt", "w");

    if (file == NULL) {
        printf("error");
        exit(1);
    }

    while (!feof(file)) {

        double chng = (chg / 100);
        double pric = atof(mv.price);
        pric = pric + pric * chng;

        puts("--------------------------");
        fgets(mv.ID, 6, file);
        printf("ID:%s", mv.ID);
        fgets(mv.ttle, 50, file);
        printf("TITLE: %s", mv.ttle);
        fgets(mv.author, 80, file);
        printf("AUTHOR: %s", mv.author);
        fgets(mv.year, 7, file);
        printf("YEAR: %s", mv.year);
        fgets(mv.price, 7, file);
        sprintf(mv.price, "%.2f\n", pric);
        printf("PRICE: %s", mv.price);

        puts("--------------------------");

        fprintf(file, "%s%s%s%s%s", mv.ID, mv.ttle, mv.author, mv.year, mv.price);
        fflush(file);
    }
    fclose(file);
}
IrAM
  • 1,720
  • 5
  • 18
nixk23213
  • 1
  • 1
  • Read this: [**Why is “while ( !feof (file) )” always wrong?**](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Andrew Henle Dec 08 '20 at 16:03
  • I've read it before, but I don't see how that could apply to this issue. Because the issue that I am having is occurring with an issue in the mode whenever I try to give it permission to write, append, append+, read+, write+. But if I use to read it will open. but other than read It will not open the file or do anything. So the issue is occurring before the while loop. and is happening when I am trying to give it a mode. – nixk23213 Dec 08 '20 at 16:10
  • Common serialisation: open it for reading, read it all into memory, close it, do modifications in memory, and then open it for writing and overwrite it all. – Neil Dec 08 '20 at 18:15
  • I tried but it won't open in write mode – nixk23213 Dec 09 '20 at 21:18

0 Answers0