Help with Struct and File Manipulation (C)

Asked

Viewed 241 times

0

Hi, I need you to help me... I did this algorithm to register the "interviews" of employees, and whenever I want to fetch an employee, I simply put his name and all the data relating to him appear. The program is working properly, however, the ".txt file" which in my case is "reply.txt" is saving as BINARY...(And is with some strange symbols)... helppp

CODE:

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


typedef struct contato CONTATO;
struct contato{
    char    nome[30];
    char    sexo[15];
    char    idade[5];
    float   renda;
    char    fumante[5];
    char    esportes[5];
    char    atividadef[5];
};

void cabecalho();
void cabecalho2();
void inputCTT();
void pesquisar();

int main(){

        int opcao;

        do{
                cabecalho();
                scanf("%d", &opcao);

                switch (opcao){
            case 1:
                inputCTT();
                break;
            case 2:
                pesquisar();
                break;

            case 3:
                printf("--------------------\n");
                printf("Volte sempre! =D \n");
                printf("--------------------\n");
                getch();
                break;

            default:
                printf("-----------------------\n");
                printf("Opcao invalida...\n");
                printf("-----------------------\n");
                getch();
                break;
            }
        }while (opcao != 3);

}

void cabecalho(){
    system("cls");
            printf("\n\t\t\t\t ALCATRAZ LTDA\n");
            printf("\t\t\t------------------------------\n");
            printf("\t\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\n");
            printf("\t\xBA Para realizar uma nova entrevista: Digite [1]            \xBA\n");
            printf("\t\xBA                                                          \xBA\n");
            printf("\t\xBA Para realizar uma busca no banco de dados: Digite [2]    \xBA\n");
            printf("\t\xBA                                                          \xBA\n");
            printf("\t\xBA Para sair: Digite [3]                                    \xBA\n");
            printf("\t\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\n");
}
void cabecalho2(){
            system("cls");
            printf("\n\t\t\t\t ALCATRAZ LTDA\n");
            printf("\t\t\t------------------------------\n");
}

void inputCTT(){


        FILE* resposta;
        CONTATO ctt;

        resposta = fopen("resposta.txt", "a");

        if (resposta == NULL){
            printf("Erro na abertura do arquivo...\n");
        }
        else{
            do{
                    cabecalho2();


                    fflush(stdin);
                    printf("\n");
                    printf("Nome: ");
                    gets(ctt.nome);


                    fflush(stdin);
                    printf("Sexo: [Masculino] / [Feminino] / [Outro]: ");
                    gets(ctt.sexo);

                    fflush(stdin);
                    printf("Idade: ");
                    gets(ctt.idade);


                    fflush(stdin);
                    printf("Renda: ");
                    scanf("%f", &ctt.renda);


                    fflush(stdin);
                    printf("Fumante: [Sim/Nao]: ");
                    gets(ctt.fumante);



                    fflush(stdin);
                    printf("Gosta de esportes:  [Sim/Nao]: ");
                    gets(ctt.esportes);


                    fflush(stdin);
                    printf("Pratica atividade fisica: [Sim/Nao]: ");
                    gets(ctt.atividadef);

                    fwrite(&ctt, sizeof(CONTATO),1, resposta);



                printf("\n\nDeseja continuar: [S/N]?\n");
            }
            while(getche() != 'n');

                fclose(resposta);
        }

}

void pesquisar(){
    FILE* resposta;
    CONTATO ctt;
    char nome[30];

    cabecalho2();

    resposta = fopen("resposta.txt", "rt");

    if (resposta == NULL){
        printf("Erro na abertura do arquivo...\n");
    }else{
        fflush(stdin);
        printf("Digite o nome a pesquisar: ");
        gets(nome);

        while(fread(&ctt, sizeof(CONTATO), 1, resposta)==1 ){
                if (strcmp(nome, ctt.nome)==0){
                    printf("\nNome: %s\n", ctt.nome);
                    printf("Sexo: %s\n", ctt.sexo);
                    printf("Idade: %s\n", ctt.idade);
                    printf("Renda Mensal: %.f\n", ctt.renda);
                    printf("Fumante: %s\n", ctt.fumante);
                    printf("Gosta de esportes: %s\n", ctt.esportes);
                    printf("Pratica atividade fisica: %s\n", ctt.atividadef);
                }
        }

    }
    fclose(resposta);
    getch();
}

  • I used CODE::BLOCKS. I just needed the "reply.txt" to be readable...

  • Do you want to resposta.txt can be read by notepad, for example?

  • It is already being read. But it was like binary... But the solution below was very responsive, thanks.

1 answer

0


At the time of writing in the file, the fwrite(&ctt, sizeof(CONTATO),1, resposta) is passing through all vector positions, including those that have not been filled. These strange symbols are these empty spaces, memory junk or that signal the end of the string.

Replace the above command with fprintf, looking for a string inside the char vector, instead of writing everything in it.

// Dentro da função inputCTTT(), após ler as entradas
fprintf(resposta, "%s\n%s\n%s\n%f\n%s\n%s\n%s\n", ctt.nome, ctt.sexo, ctt.idade, ctt.renda, ctt.fumante, ctt.esportes, ctt.atividadef);

After registering two people, for example, your file resposta.txt will look like this:

Joao // Início do primeiro registro
Masculino
23
1234.56
Nao
Sim
Nao
Maria // Início do segundo registro
Feminino
32
6543.21
Sim
Nao
Sim

To search for the data in the file with this formatting, you can use the fscanf, however, if the name is not found on the current line, you should skip 7 lines (the name line has already been read for comparison), where the next name is:

// Dentro da função pesquisar(), após ler o nome (a ser pesquisado)
while (1){
    fscanf(resposta, "%s", &ctt.nome); // Lê o nome no arquivo
    if (strcmp(nome, ctt.nome) == 0){
        fscanf(resposta, "%s %s %f %s %s %s", &ctt.sexo, &ctt.idade, &ctt.renda, &ctt.fumante, &ctt.esportes, &ctt.atividadef);
        printf("\nNome: %s\n", ctt.nome);
        printf("Sexo: %s\n", ctt.sexo);
        printf("Idade: %s\n", ctt.idade);
        printf("Renda Mensal: %.f\n", ctt.renda);
        printf("Fumante: %s\n", ctt.fumante);
        printf("Gosta de esportes: %s\n", ctt.esportes);
        printf("Pratica atividade fisica: %s\n", ctt.atividadef);
        break;
    } else {
        // Move o ponteiro do arquivo 7 linhas
        int i = 0;
        while (i < 7) {
            if(feof(resposta)) { // Fim do arquivo
                printf("Nome nao encontrado");
                fclose(resposta);
                getch();
                return;
            }
            if (fgetc(resposta) == '\n')
                i++;
        }
    }
}
  • That’s right, thank you. It worked almost perfectly, however, it is not finding the second name... When I look for the second name saved or the third name saved, it does not appear anything. Then I press [ENTER] and go back to the main menu (Header)

  • Strange, because the only way out of this loop is to find the name (by break) or in the if(feof(resposta)) (for return), where there is a printf("Nome nao encontrado"). But nothing appears in yours? Here is working normally

  • Dude, I just did it. The "bug" is right there in the sign. While (i < 7) = Wrong! While (i >7) = Right! Muitoooo thanks. = D

  • Good haha, by the way I loved your header/menu!

  • kkk, thanks. It’s for a Fac job...

Browser other questions tagged

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