0
I need to create a program that registers a user and stores their respective data in a text file. It happens to be various data (Name, CPF, Phone, Address, email, etc.). Then I created a struct full of different types, each according to the appropriate type of data (The CPF, Phone are like char because it will be only symbolic, I will not do any calculation operation with any of them, so I think char is the most appropriate). My problem is that I am repeating several functions in a very inadequate way, I think I could create functions() to make the code cleaner and less repetitive, but I can’t think of a suitable solution. Here’s the code to make it clearer:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct paciente {
char nome[MAX];
char CPF[MAX];
char tel[MAX];
};
int main()
{
struct paciente paciente;
FILE *dadospaciente;
dadospaciente = fopen("paciente.txt", "w");
if (dadospaciente == NULL)
{
printf("Error!\n");
exit(1);
}
// Entrada de dados da struct paciente & salvar dados em arquivo de texto
printf("\nEntre com o nome: ");
//scanf("%s", paciente.nome);
fgets(paciente.nome, MAX, stdin);
fprintf(dadospaciente, "Nome do paciente: %s", paciente.nome);
//fclose(dadospaciente);
printf("\nEntre com o CPF: ");
fgets(paciente.CPF, MAX, stdin);
fprintf(dadospaciente, "\nCPF: %s", paciente.CPF);
printf("\nTelefone: ");
fgets(paciente.tel, MAX, stdin);
fprintf(dadospaciente, "\nTelefone: %s", paciente.tel);
fclose(dadospaciente);
return 0;
}
That’s just code for testing. As you can see, I am repeating every time the process of capturing strings, and doing the same process for all the data I mentioned at the beginning of the question will be very extensive and I think there should be another solution to this. How can I repeat the same process without copying and pasting the code and only changing the variables? Thank you from now
The function
fgets
keeps the end-of-line character ('\n'
) as part of the string read (provided it is smaller than the maximum size). Depending on how you will read the saved file in this program you may have problems. Usually when using data organized in a struct the write and read is done in binary mode and not text. As for the reading of the data you have to do field by field but the recording of the file can be done only once of the whole structure.– anonimo