Skip to content

Instantly share code, notes, and snippets.

@drmcarvalho
Last active December 3, 2016 01:30
Show Gist options
  • Save drmcarvalho/aeff44bd4ccd2f514b1206a20832912b to your computer and use it in GitHub Desktop.
Save drmcarvalho/aeff44bd4ccd2f514b1206a20832912b to your computer and use it in GitHub Desktop.
Exemplo de cadastro em arquivo txt.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**Constantes**/
#define ARQUIVO_PESSOAS "pessoas.txt"
#define LEITURA "r"
#define GRAVACAO "a+"
typedef struct pessoa
{
char *nome;
int idade;
}Pessoa;
void lerPessoa(Pessoa *);
void salvarEmArquivo(Pessoa);
void relatorioCadastroPessoa(char *);
int main(void)
{
Pessoa obj, *ptr;
ptr = &obj;
lerPessoa(ptr);
salvarEmArquivo(obj);
system("clear");
printf("Pessoas cadastras:\n\n");
relatorioCadastroPessoa(ARQUIVO_PESSOAS);
return EXIT_SUCCESS;
}
void lerPessoa(Pessoa * ptrObj)
{
printf("\nNome: ");
fgets(ptrObj->nome, sizeof(ptrObj->nome), stdin);
ptrObj->nome[strcspn(ptrObj->nome, "\n")] = 0;
printf("\nIdade: ");
scanf("%i", &ptrObj->idade);
}
void salvarEmArquivo(Pessoa obj)
{
FILE * escreveArquivo = fopen(ARQUIVO_PESSOAS, GRAVACAO);
if (!escreveArquivo)
return;
fprintf(escreveArquivo, "Nome: %s | ", obj.nome);
fprintf(escreveArquivo, "Idade: %i", obj.idade);
fprintf(escreveArquivo, "\n");
fclose(escreveArquivo);
}
void relatorioCadastroPessoa(char * nomeArquivo)
{
FILE * arquivoLeitura = fopen(nomeArquivo, LEITURA);
char line[256];
if (arquivoLeitura) {
while (fgets(line, sizeof(line), arquivoLeitura))
printf("%s", line);
fclose(arquivoLeitura);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment