Search in file . txt

Asked

Viewed 478 times

0

I’m doing a college paper that’s asked to do a library book registration system, The whole part of the registration is already ready but the research part is missing, which is where I don’t know how to do it because I’m new to the C language area and I’m leaving my code here so I can take a look and maybe help me to do a search in a file. txt

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

void menu(){

    printf ("\n\n1 - Cadastrar\n");
    printf ("2 - Listar todos os livros.\n");
    printf ("3 - Listar todas as revistas.\n");
    printf ("4 - Listar as obras por caixa.\n");
    printf ("0 - Sair\n");
}

FILE* AbreArquivo(char modo, char caminho[100]){

    FILE *arquivo;
    switch(modo){

        case 'g':
            arquivo = fopen(caminho,"wt");
            break;
        case 'l':
            arquivo = fopen(caminho,"rt");
            break;
        case 'a':
            arquivo = fopen(caminho,"a");
            break;
    }

    if(arquivo==NULL){

        printf("Nao foi possivel abrir o arquivo");
        exit(0);

    }

    return arquivo;
}

void FecharArquivo(FILE *arquivo){

    fclose(arquivo);

}

void Cadastra(char titulo[1000],char editora[1000], char autor[1000], int caixa, int ano, int ISBN){

    FILE *arquivo;
    arquivo = AbreArquivo('a', "livros.txt");
    fprintf(arquivo, "%s  %s  %s  %d  %d  %d\n\n", titulo, autor, editora, caixa, ano, ISBN);

    FecharArquivo(arquivo);
}

void CadastraRevista(char titulo[70],char editora[70], char autor[70], int caixa, int ano, int ISBN){

    FILE *arquivo;
    arquivo = AbreArquivo('a', "revistas.txt");
    fprintf(arquivo, "%s %s %s %d %d %d\n\n", titulo, autor, editora, caixa, ano, ISBN);
    FecharArquivo(arquivo);
}

void Listar(){
    FILE *arquivo;
    char titulo[1000];
    char autor[1000];
    char editora[1000];
    int caixa;
    int ano;
    int ISBN;
    arquivo = AbreArquivo('l',"livros.txt");
    printf("\t\t\t\t\t\tListando Livros....\n\n");
    while(!feof(arquivo)){
        fscanf(arquivo,"%1000[^\n] %1000[^\n] %1000[^\n] %d %d %d\n", &titulo, &autor, &editora, &caixa, &ano, &ISBN);
        setbuf(stdin,NULL);
        for(int i=0; i<120; i++)printf ("*");
        printf("\nTitulo: %s\n  \nAutor: %s\n   \nEditora: %s\n   \nCaixa: %d\n   \nAno: %d\n   \nISBN: %d\n\n", titulo, editora, autor, caixa, ano, ISBN);
    }
    FecharArquivo(arquivo);

}

void ListarRevista(){
    FILE *arquivo;
    char titulo[1000];
    char autor[1000];
    char editora[1000];
    int caixa;
    int ano;
    int ISBN;
    arquivo = AbreArquivo('l',"revistas.txt");
    printf("\t\t\t\t\t\tListando Revistas....\n\n");
    while(!feof(arquivo)){
        fscanf(arquivo,"%70[^\n] %70[^\n] %70[^\n] %d %d %d\n", &titulo, &autor, &editora, &caixa, &ano, &ISBN);
        setbuf(stdin,NULL);
        for(int i=0; i<120; i++)printf ("*");
        printf("\nTitulo: %s\n  \nAutor: %s\n   \nEditora: %s\n   \nCaixa: %d\n   \nAno: %d\n   \nISBN: %d\n\n", titulo,editora ,autor , caixa, ano, ISBN);
    }
    FecharArquivo(arquivo);

}

int main(){

    char titulo[1000];
    char autor[1000];
    char editora[1000];
    int caixa;
    int ano;
    int ISBN;
    int opcao;
    int opcao2;
    int voltar;

    topo:
    

    do{
        menu();
        printf("\nDigite uma opcao: ");
        scanf("%d", &opcao);
        setbuf(stdin,NULL);
        system("cls");
        if (opcao == 1 ){
            printf("\t\t\t\t\t\tOBS:NAO USAR ACENTOS\n");
            printf("\nDigite 1 para livros ou 2 para revistas: ");
            scanf("%d", &opcao2);
            system("cls");
        }else{
            goto listagem;
        }
            Cad:
        switch(opcao2){
            case 1:

                printf("\t\t\t\t\t\tCadastrando Livros...\n\n");
                printf("\nDigite o titulo: ");
                setbuf(stdin,NULL);
                fgets(titulo, 1000, stdin);

                printf("\nDigite o autor: ");
                setbuf(stdin,NULL);
                fgets(autor,1000, stdin);

                printf("\nDigite o editora: ");
                setbuf(stdin,NULL);
                fgets(editora, 1000, stdin);

                printf("\nDigite a caixa: ");
                scanf("%d", &caixa);

                printf("\nDigite o ano: ");
                scanf("%d", &ano);

                printf("\nDigite o ISBN: ");
                scanf("%d", &ISBN);
                Cadastra(titulo, autor, editora, caixa, ano, ISBN);
                printf("\n Digite 1 para continuar cadastrando e 2 para voltar ao menu: ");
                scanf("%d", &voltar);
                if(voltar==2){
                  system("cls");
                  goto topo;
                }else{
                    system("cls");
                    goto Cad;
                }
                system("cls");

                break;

            case 2:

                printf("\t\t\t\t\t\tCadastrando Revistas...\n\n");
                printf("\nDigite o titulo: ");
                setbuf(stdin,NULL);
                fgets(titulo, 100, stdin);

                printf("\nDigite o autor: ");
                setbuf(stdin,NULL);
                fgets(autor,70, stdin);

                printf("\nDigite o editora: ");
                setbuf(stdin,NULL);
                fgets(editora, 70, stdin);

                printf("\nDigite a caixa: ");
                scanf("%d", &caixa);

                printf("\nDigite o ano: ");
                scanf("%d", &ano);

                printf("\nDigite o ISBN: ");
                scanf("%d", &ISBN);
                CadastraRevista(titulo, autor, editora, caixa, ano, ISBN);
                printf("\n Digite 1 para continuar cadastrando e 2 para voltar ao menu: ");
                scanf("%d", &voltar);
                if(voltar==2){
                  system("cls");
                  goto topo;
                }else{
                    system("cls");
                    goto Cad;
                }
                system("cls");
                break;
        }

    }while(opcao!=0);

    listagem:
    switch(opcao){
            case 2:
                Listar();
                system("pause");
                system("cls");
                goto topo;
                break;

            case 3:
                ListarRevista();
                system("pause");
                system("cls");
                goto topo;
                break;

            case 4:
                printf("Opcao nao funcional!\n\n");
                system("pause");
                system("cls");
                goto topo;

            case 0:
                printf("Finalizando......\n\n");
                system("pause");
                exit(0);

            default:
                printf("Erro ");
                system("pause");
                system("cls");
                goto topo;
    }
    return 0;
}
  • 1

    I refuse to analyze a program that uses goto.

2 answers

0

Your program looks very complicated without need. Write your program around the data. Always.

In general, when asked for this type of solution for a student, he has already learned about structures, data structures and memory allocation. I don’t know if it’s your case.

I’ll give you a few guesses only, after all it’s been a long time. If you still need help write again.

Back to the problem

You have one or more files on disk with the collection, because it seems that you keep magazines and books in separate files, and there are some things you need to do with the collection, like list them all by some criteria or edit.

In C you can group data into a structure, thus declaring

typedef struct
{
    char    titulo[40];
    char    editora[40];
    char    autor[40];
    int     caixa;
    int     ano;
    char    ISBN[20]; // 123-4-56-789ABC-D
    char    tipo; // 'L' para livro
}   Livro;

A Book. Note that you can use more modest sizes for the fields. 1,000 letters is a bit exaggerated for author, title or publisher as you had used. And int for ISBN, a format established worldwide, is wrong.

And the acervo is a collection of Livro. There is no reason to use two files unless the statement requires it. And a collection can be something as minimal as

typedef struct
{
    int     total;
    Livro   livro[200]
}   Acervo;

And a library could be something like this

Acervo    loja1;
loja1.total = 0;

To start reading from the disk the store’s collection 1.

In general, dynamic memory allocation would be used for all these fields. And often a linked list or other data structure for the books. But it may even be a simple vector.

And the files?

In general at the input the file data is all read to a vector of structures in memory. All processing is done in this structure. At the end of the program the structure is copied back to the disk with another name. This changes the name of the original file to a backup extension and changes the new file to the original name. So if you started with "txt books." will end with "txt books." and "Bak books.". Unoriginal.

Often each edit is saved to disk in a file when the content is important. Something like a transaction file, a log. So if the program cancels after hours of editing you can enter a program that opens the original file and this log of transactions and updates everything before re-running.

It is not edited directly in the file because it is problematic at the very least. It is possible and simple, are few functions to position the file, find a record, rewrite a stretch and such. Just not worth the effort unless the statement requires using it. Simple functions like rewind() fseek() fopen(), fclose() and family.

0

Strings handling in C is a bit more complicated than in most languages.

To do searches in text files in C you must make a LOOP reading the entire file and checking character by character to find the STRING you are searching for.

Example:

FILE *f = fopen("arquivo.txt", "r");
char c;
int i;
char* string_pesquisar = "Revista Epoca";
while((c = fgetc(f)) != EOF){
    if(c == *string_pesquisar){ //Primeiro caracter da STRING que estamos buscando foi encontrado, vamos checas os subsequentes:

        for(i = 0; i < strlen(string_pesquisar); i ++){ //loop para comparar cada caracter da String pesquisada com o proximo caracter lido
            c = fgetc(f); //lê mais um caracter no arquivo
            if(c == EOF)  //se encontrar o final do arquivo sai do loop
                break;
            if(*(string_pesquisar + i) != c) //se algum caracter subsequente lido for diferente da string pesquisada sai do loop
                break;
        }

        if(i == strlen(string_pesquisar){ //se i == qtd caracteres da String a pesquisar então achamos a string (a verificação não foi interrompida durante as comparações de caracteres)
             //Aqui entra o seu código ao achar a STRING que você procurava

             break; //break para parar de ler o arquivo
        }
     }
}

fclose(f);

There is a HEADER for C with functions for string manipulation in addition to the string. h, you can find it here: https://gist.github.com/raphaelnapi/ed0c29e049ee6dd0d36d687b77b9ee0a

With this header in your project you can use the instr() function to search one string within another. It will return the position of the first character of the searched String or -1 if it does not find it.

Example:

instr(0, "Código escrito em C", "escrito");

This call for the instr() function will fetch the "written" string inside the "Code written in C" string from position 0 (first character) and return an integer with value 7 (position of the 'and' letter of the "written" string in the first string).

Note that you should differentiate minusculas from maiusculas. For this it is interesting to make all the characters of the STRING to be searched and the STRING searched are minuscules before performing the search. With this HEADER you can do this with the Lower function().

Browser other questions tagged

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