fread e fseek in c

Asked

Viewed 92 times

0

Write a program using fwrite and fread that asks the user the type of shopping list he wants to create: Bakery or Barbecue. The program must save the items in a text file until the user type 0 (zero), being as follows, for example:

BARBECUE BAKERY

charcoal bread

picanha butter

soft coffee

.... ....

Note: Develop a program that reads the contents of the file backwards, for this use fread() and fseek.

My question is on how to use fread and fseek in this case.

#include <stdlib.h>
#include <locale.h>
#include <string.h>
int main (){
    char nomePad[50], nomeChu[50];
    nomePad[0] = '\0', nomeChu[0] = '\0';
    int x = 0, op;
    FILE *lista;
    setlocale(LC_ALL,"");
    printf ("Digite uma opção: \n");
    printf ("\n1 - Padaria;\n");
    printf ("2 - Churrasco.\n");
    scanf ("%d", &op);
    if ((lista = fopen("lista.bin", "wb")) == NULL){
        printf ("Erro no arquivo.\n");
    }
    else {
        if (op == 1){
            fprintf (lista, "\nPADARIA\n\n");
            while (nomePad[x] != '0'){
                printf ("Digite o item: ");
                scanf ("%s[^\n]", nomePad);
                setbuf(stdin, 0);
                fwrite (nomePad[x], sizeof(nomePad), x, lista);
            }
        }
        else{
            fprintf (lista, "\nCHURRASCO\n\n");
            while (nomeChu[x] != '0'){
                printf ("Digite o item: ");
                scanf ("%s[^\n]", nomeChu);
                setbuf(stdin, 0);
                fwrite (&nomeChu[x], sizeof(char), x, lista);
            }
        }
        fclose (lista);
    }
    if ((lista = fopen("lista.bin", "rb")) == NULL){
        printf ("Erro no arquivo.\n");
    }
    else {
        fseek(lista, 0, SEEK_END);
        fread(&nomeChu[x], sizeof(char), 50, lista);
        fread(nomePad[x], sizeof(nomePad), x, lista);
        printf("%s\n%s\n", nomePad, nomeChu);
        fclose(lista);
    }
    return 0;
}
  • Do not mix fprint with fwrite. Remember that fread() and fwrite() serve to work with files that contain blocks of data of defined size.You’re also confusing a string with a character at a given string position.

  • Thanks for your help

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.