-1

I've made a program that reads a file named "books.txt" and displays its contents. In the file, there is a price for each of the 4 books.

I'm not sure how to make my program increase the price of the book (percent) depending on user inputs; for example, the user is prompted to enter a number and that number (which is a percentage) is multiplied by the price of each book and gives the updated price.

How do I do it?

Here's my code:

int main() {
    /* File pointer to hold reference to our file */
    FILE * fPtr;
    char buffer[BUFFER_SIZE];
    int totalRead = 0;
    /* 
     */
    fPtr = fopen("books.txt", "r");
    
    if (fPtr == NULL) {
      printf("Unable to open file.\n");
      printf("Please check whether file exists and you have read privilege.\n");
      exit(EXIT_FAILURE);
    }

    printf("File opened successfully. Reading file contents line by line. \n\n");
   
    while (fgets(buffer, BUFFER_SIZE, fPtr) != NULL) {
      totalRead = strlen(buffer);
      /*
       */
      buffer[totalRead - 1] = buffer[totalRead - 1] == '\n' 
                              ? '\0' 
                              : buffer[totalRead - 1];
      printf("%s\n", buffer);
    } 
    
    fclose(fPtr);

    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
ibo salaj
  • 11
  • 2
  • This is a very unclear question. Can you at least provide some sample input and expected output? – h0r53 Dec 09 '20 at 19:45
  • example: https://gyazo.com/2422876736f5351dd54f207feaf3bdd2 – ibo salaj Dec 09 '20 at 19:47
  • 1
    Please do not provide links to other sites. StackOverflow has all of the resources necessary for asking questions. Please see https://stackoverflow.com/help/how-to-ask – h0r53 Dec 09 '20 at 19:48

1 Answers1

0

You can read the file and store all the book data in some array of struct such as

typedef struct {
    int id;
    char *title;
    char *author;
    int year;
    float price;
}Book;

Then ask for the percentage to the user and re-write the file calculating the new price for each Book (price += percentage/100)

To re-write the file you need to open the file with "w permits. You can check for documentation here. Don't forget to close fPtr before opening the same file again with write permits

user157629
  • 624
  • 4
  • 17