Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Sistema de Controle de Clientes
- //
- // Criado por Sergio Toledo Piza
- // Copyright © 2016. Nenhum direito reservado.
- //
- // Agradecimentos especiais ao Google e ao Stackoverflow
- //
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #include <ctype.h>
- #include <locale.h>
- #include <string.h>
- struct client {
- int id;
- char name[30];
- char address[50];
- char city[30];
- char country[20];
- char cep[10];
- char dob[15];
- char phone[16];
- float total;
- };
- int i, j, total_clients = 0, capacity = 1;
- struct client a[1];
- float strToFloat(char str[]) {
- int size = strlen(str);
- char str2[size];
- for (i = 0; str[i]; i++) {
- if (str[i] == '.') {
- str2[i] = ',';
- } else str2[i] = str[i];
- }
- str2[size] = '\0';
- printf("\n%.2f\n", strtod("30,30", NULL));
- return strtod(str2, NULL);
- }
- void readLine(char *line, struct client *client) {
- int substr_end = 0, info_id = 1;
- int line_size = strlen(line);
- char substr[line_size];
- for (i = 0; i < line_size; i++) {
- char ch = line[i];
- if (ch != ';' && ch != '\n' && ch != EOF) {
- substr[substr_end] = ch;
- substr_end++;
- } else {
- substr[substr_end] = '\0';
- //printf("%s %i\n", substr, info_id);
- switch(info_id) {
- case 1: // id
- client->id = atoi(substr);
- break;
- case 2: // name
- strcpy(client->name, substr);
- break;
- case 3:
- strcpy(client->address, substr);
- break;
- case 4: // city
- strcpy(client->city, substr);
- break;
- case 5: // country
- strcpy(client->country, substr);
- break;
- case 6: // cep
- strcpy(client->cep, substr);
- break;
- case 7: //date of birth
- strcpy(client->dob, substr);
- break;
- case 8: // phone number
- strcpy(client->phone, substr);
- break;
- case 9: // sales total
- client->total = strToFloat(substr);
- break;
- default:
- i = line_size;
- break;
- }
- substr_end = 0;
- substr[0] = '\0';
- info_id++;
- }
- }
- }
- void printClient(struct client client) {
- printf("Cliente %s:\n", client.name);
- printf("- ID: %i\n", client.id);
- printf("- Endereço: %s\n", client.address);
- printf("- Cidade: %s\n", client.city);
- printf("- País: %s\n", client.country);
- printf("- CEP: %s\n", client.cep);
- printf("- Data de Nascimento: %s\n", client.dob);
- printf("- Telefone: %s\n", client.phone);
- printf("- Total Vendas: R$%.2f\n", client.total);
- }
- void growArray(struct client **a, int total, int *capacity) {
- if (total == *capacity) {
- *capacity *= 2;
- *a = (struct client*)realloc(*a, *capacity*sizeof(struct client));
- }
- }
- struct client addClient(struct client **a, int *total, int *capacity) {
- struct client newClient = {
- *total + 1,
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- 0
- };
- printf("ID do novo cliente: %i\n", *total + 1);
- //newClient.id = *total + 1;
- while (strlen(newClient.name) < 1) {
- printf("Digite o nome do novo cliente: ");
- gets(newClient.name);
- fflush(stdin);
- if (strlen(newClient.name) > 0)
- break;
- printf("Digite um nome!\n");
- }
- while (strlen(newClient.address) < 1) {
- printf("Digite o endereço do novo cliente: ");
- gets(newClient.address);
- fflush(stdin);
- if (strlen(newClient.address) > 0)
- break;
- printf("Digite um endereço!\n");
- }
- while (strlen(newClient.city) < 1) {
- printf("Digite a cidade do novo cliente: ");
- gets(newClient.city);
- fflush(stdin);
- if (strlen(newClient.city) > 0)
- break;
- printf("Digite uma cidade!\n");
- }
- while (strlen(newClient.country) < 1) {
- printf("Digite o país do novo cliente: ");
- gets(newClient.country);
- fflush(stdin);
- if (strlen(newClient.country) > 0)
- break;
- printf("Digite um país!\n");
- }
- while (strlen(newClient.cep) < 9) {
- printf("Digite o cep do novo cliente (12345-678): ");
- gets(newClient.cep);
- fflush(stdin);
- if (strlen(newClient.cep) >= 9)
- break;
- printf("Digite um cep válido!\n");
- }
- while(strlen(newClient.dob) != 10) {
- printf("Digite a data de nascimento do novo cliente (dd/mm/aaaa): ");
- gets(newClient.dob);
- fflush(stdin);
- if (strlen(newClient.dob) == 10)
- break;
- printf("Digite uma data válida!\n");
- }
- while (strlen(newClient.phone) < 10) {
- printf("Digite o telefone do novo cliente ( (00) 99999-9999 ): ");
- gets(newClient.phone);
- fflush(stdin);
- if (strlen(newClient.phone) >= 10)
- break;
- printf("Digite um telefone válido!\n");
- }
- char aux[10];
- do {
- printf("Digite o total de vendas do novo cliente: ");
- gets(aux);
- fflush(stdin);
- if (strlen(aux) > 0)
- break;
- printf("Digite um valor!\n");
- } while (strlen(aux) < 1);
- newClient.total = strToFloat(aux);
- system("cls");
- printClient(newClient);
- while (1) {
- printf("\nDeseja adicionar esse cliente? <s/n>: ");
- switch(tolower(getche())) {
- case 's':
- *total += 1;
- growArray(a, *total, capacity);
- return newClient;
- break;
- case 'n':
- newClient.id = -1;
- return newClient;
- break;
- default:
- printf("\nDigite um valor válido!");
- break;
- }
- }
- }
- void printAllClients(struct client *a, int total, char sort_by) {
- struct client b[total];
- for (i = 0; i < total; i++)
- b[i] = a[i]; // To not modify the main array
- if (sort_by == 'i') {
- //https://www.vivaolinux.com.br/script/Ordenacao-QuickSort
- struct client aux;
- int left = 0, right = total - 1, x;
- quick:
- x = left;
- for(i = left + 1; i <= right; i++){
- j = i;
- if(b[j].id < b[x].id){
- aux = b[j];
- while(j > x){
- b[j] = b[j-1];
- j--;
- }
- b[j] = aux;
- x++;
- }
- }
- if(x-1 >= left){
- right = x - 1;
- goto quick;
- }
- if(x+1 <= right){
- left = x + 1;
- goto quick;
- }
- for (i = 0; i < total; i++) {
- printf("ID: %i; Nome: %s; Endereço: %s; Cidade: %s; País: %s; Cep: %s; Data de nascimento: %s; Telefone: %s; Total vendas: R$%.2f\n\n", b[i].id, b[i].name, b[i].address, b[i].city, b[i].country, b[i].cep, b[i].dob, b[i].phone, b[i].total);
- }
- }
- if (sort_by == 'n') {
- for (j = 0; j < total - 1; j++) {
- for (i = 0; i < total - 1; i++) {
- if (0 < strcmp(b[i].name, b[i +1].name)) {
- struct client pchTemp = b[i];
- b[i] = b[i +1];
- b[i +1] = pchTemp;
- }
- }
- }
- for (i = 0; i < total; i++) {
- printf("Nome: %s; ID: %i; Endereço: %s; Cidade: %s; País: %s; Cep: %s; Data de nascimento: %s; Telefone: %s; Total vendas: R$%.2f\n\n", b[i].name, b[i].id, b[i].address, b[i].city, b[i].country, b[i].cep, b[i].dob, b[i].phone, b[i].total);
- }
- }
- if (sort_by == 't') {
- // By Sergio Toledo Piza
- for (i = 0; i < total; i++) {
- int lower_index = i;
- float lower_number = b[i].total;
- for (j = i + 1; j < total; j++) {
- if (b[j].total < lower_number) {
- lower_index = j;
- lower_number = b[j].total;
- }
- }
- struct client x = b[i];
- b[i] = b[lower_index];
- b[lower_index] = x;
- }
- for (i = 0; i < total; i++) {
- printf("Total vendas: R$%.2f; ID: %i; Endereço: %s; Nome: %s; Cidade: %s; País: %s; Cep: %s; Data de nascimento: %s; Telefone: %s;\n\n", b[i].total, b[i].id, b[i].name, b[i].address, b[i].city, b[i].country, b[i].cep, b[i].dob, b[i].phone);
- }
- }
- }
- char menu() {
- printf("*********************************\n");
- printf("** Sistema de Controle **\n");
- printf("** de Clientes **\n");
- printf("** **\n");
- printf("** Feito por: **\n");
- printf("** Sergio Toledo Piza **\n");
- printf("*********************************\n");
- printf("** **\n");
- printf("** 1 - Adicionar cliente **\n");
- printf("** 2 - Modificar cliente **\n");
- printf("** 3 - Excluir cliente **\n");
- printf("** 4 - Pesquisar cliente **\n");
- printf("** 5 - Exibir clientes **\n");
- printf("** Esc - Sair do programa **\n");
- printf("** **\n");
- printf("*********************************\n\n");
- printf("Digite sua opção: ");
- return getche();
- }
- int saveFile(struct client *a, char *filename) {
- FILE *f = fopen(filename, "w");
- if (f == NULL) {
- printf("Erro ao salvar arquivo!\n");
- return;
- }
- printf("Aguarde! Salvando arquivo...\n");
- int hasDeletedClients = 0;
- for (i = 0; a[i].id; i++) {
- if (a[i].id != i + 1 && a[i].id != -1) {
- a[i].id = i + 1;
- hasDeletedClients = 1;
- }
- if (a[i].id != -1)
- fprintf(f, "%i;%s;%s;%s;%s;%s;%s;%s;%.2f\n", a[i].id, a[i].name, a[i].address, a[i].city, a[i].country, a[i].cep, a[i].dob, a[i].phone, a[i].total);
- else
- hasDeletedClients = 1;
- }
- printf("Arquivo salvo!\n");
- fclose(f);
- return hasDeletedClients;
- }
- char *strtolower(char str[]) {
- char *x = str;
- for (j = 0; j < x[j]; j++) {
- x[j] = tolower(x[j]);
- }
- return x;
- }
- struct client searchClient(struct client *a, int id, char name[], char searchType) {
- struct client notFound;
- notFound.id = -1;
- if (id == 0 && searchType == 'i') {
- printf("Operação de busca cancelada!\n");
- return notFound;
- }
- for (i = 0; a[i].id; i++) {
- if (searchType == 'i') {
- if (a[i].id == id) {
- return a[i];
- }
- } else {
- char name_search[30]; // To not directly modify the client's name
- strcpy(name_search, a[i].name);
- if (strcmp(strtolower(name_search), strtolower(name)) == 0) {
- return a[i];
- }
- }
- }
- return notFound;
- }
- int editClient(struct client *a, int client_id) {
- if (a->id != client_id) {
- printf("Erro ao processar ID do cliente!\n");
- return 1;
- }
- int didPressEsc = 0;
- editClientForm:
- printf("Modificando ");
- printClient(*a);
- printf("\n");
- printf("********************************************************\n");
- printf("* 1: Endereço 4: CEP 7: Total Vendas *\n");
- printf("* 2: Cidade 5: Data de Nascimento Esc: Voltar *\n");
- printf("* 3: País 6: Número de Telefone *\n");
- printf("********************************************************\n");
- printf("\nDigite o número do campo que deseja modificar: ");
- char aux = getche();
- char aux2[50];
- system("cls");
- printf("Modificando Cliente %s:\n", a->name);
- printf("Campo: ");
- switch (aux) {
- case '1':
- printf("endereço.\n");
- printf("Valor atual: %s\n", a->address);
- printf("Novo valor: ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) == 0)
- strcpy(aux2, a->address);
- strcpy(a->address, aux2);
- printf("Endereço atualizado!\n");
- break;
- case '2':
- printf("cidade.\n");
- printf("Valor atual: %s\n", a->city);
- printf("Novo valor: ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) == 0)
- strcpy(aux2, a->city);
- strcpy(a->city, aux2);
- printf("Cidade atualizada!\n");
- break;
- case '3':
- printf("país.\n");
- printf("Valor atual: %s\n", a->country);
- printf("Novo valor: ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) == 0)
- strcpy(aux2, a->country);
- strcpy(a->country, aux2);
- printf("País atualizado!\n");
- break;
- case '4':
- printf("CEP.\n");
- printf("Valor atual: %s\n", a->cep);
- printf("Novo valor (12345-678): ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) == 0)
- strcpy(aux2, a->cep);
- strcpy(a->cep, aux2);
- printf("CEP atualizado!\n");
- break;
- case '5':
- printf("data de nascimento.\n");
- printf("Valor atual: %s\n", a->dob);
- printf("Novo valor (dd/mm/aaaa): ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) == 0)
- strcpy(aux2, a->dob);
- strcpy(a->dob, aux2);
- printf("Data de nascimento atualizada!\n");
- break;
- case '6':
- printf("telefone.\n");
- printf("Valor atual: %s\n", a->phone);
- printf("Novo valor (99) 99999-9999: ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) == 0)
- strcpy(aux2, a->phone);
- strcpy(a->phone, aux2);
- printf("Telefone atualizado!\n");
- break;
- case '7':
- printf("total vendas.\n");
- printf("Valor atual: R$%.2f\n", a->total);
- printf("Novo valor: ");
- gets(aux2);
- fflush(stdin);
- if (strlen(aux2) != 0)
- a->total = strToFloat(aux2);
- printf("Total vendas atualizado!\n");
- break;
- case 27:
- system("cls");
- printf("Operação cancelada!\n");
- didPressEsc = 1;
- break;
- default:
- printf("inválido.\n");
- system("PAUSE");
- system("cls");
- goto editClientForm;
- break;
- }
- return didPressEsc;
- }
- int getNumberFromString() {
- char strn[30];
- gets(strn);
- fflush(stdin);
- return atoi(strn);
- }
- int deleteClient(struct client *a, int client_id) {
- int error = 0;
- if (a->id != client_id) {
- printf("Erro ao processar ID do cliente!\n");
- return 1;
- }
- printClient(*a);
- delete_prompt:
- printf("\nDeseja mesmo apagar este cliente? <s/n>: ");
- switch (tolower(getche())) {
- case 's':
- printf("\nCliente %s apagado!\n", a->name);
- a->id = -1;
- return 0;
- break;
- case 'n':
- printf("\nOperação cancelada!\n");
- return 1;
- break;
- default:
- printf("\nDigite uma opção válida!");
- goto delete_prompt;
- break;
- }
- printf("\nErro ao deletar cliente.\n");
- return 1;
- }
- char getche_and_clear() {
- char ch = getche();
- system("cls");
- return ch;
- }
- int empty_clients(int total) {
- if (total == 0) {
- printf("Não existe nenhum cliente registrado!\n");
- return 1;
- }
- return 0;
- }
- int main()
- {
- setlocale(LC_ALL, "portuguese");
- FILE* fh;
- char filename[30];
- printf("*********************************\n");
- printf("** Sistema de Controle **\n");
- printf("** de Clientes **\n");
- printf("*********************************\n\n");
- printf("Inicializando programa...\n");
- file_open:
- strcpy(filename, "clientes.csv");
- printf("Deseja abrir o arquivo \"%s\"? <s/n>: ", filename);
- switch (tolower(getche())) {
- case 's':
- system("cls");
- break;
- case 'n':
- printf("\nDigite o nome do arquivo que deseja abrir: ");
- gets(filename);
- fflush(stdin);
- break;
- default:
- printf("\nDigite uma opção válida!\n");
- goto file_open;
- break;
- }
- goto processClientsArray;
- reProcessClientsArray:
- printf("Corrigindo problemas...\n");
- printf("Pressione qualquer tecla para recarregar o arquivo.\n");
- system("PAUSE");
- total_clients = 0;
- system("cls");
- processClientsArray:
- fh = fopen(filename, "r");
- //check if file exists
- if (fh == NULL){
- printf("Arquivo \"%s\" não encontrado!\n", filename);
- printf("Pressione qualquer tecla para continuar.\n");
- getch();
- goto file_open;
- }
- //http://stackoverflow.com/questions/3501338/c-read-file-line-by-line
- //read line by line
- const size_t line_size = 500;
- char* line = malloc(line_size);
- total_clients = 0;
- struct client* a = (struct client*)malloc(capacity*sizeof(struct client));
- while (fgets(line, line_size, fh) != NULL) {
- growArray(&a, total_clients, &capacity);
- readLine(line, &a[total_clients]);
- total_clients++;
- }
- if (total_clients == 0)
- a[0].id = -1;
- saveFile(a, filename);
- system("cls");
- free(line);
- fclose(fh);
- //http://stackoverflow.com/questions/3501338/c-read-file-line-by-line
- char opcao;
- do {
- opcao = menu();
- int fileEdited = 0;
- struct client aux;
- system("cls");
- if (opcao == 27)
- break;
- switch(opcao) {
- case '1':
- aux = addClient(&a, &total_clients, &capacity);
- printf("\n");
- if (aux.id != -1) {
- printf("Cliente %s adicionado!\n", aux.name);
- a[total_clients - 1] = aux;
- fileEdited = 1;
- } else {
- printf("Operação cancelada!\n");
- }
- break;
- case '2':
- if (empty_clients(total_clients))
- break;
- printf("Digite o código (id) do cliente que deseja modificar: ");
- aux = searchClient(a, getNumberFromString(), "", 'i');
- int didPressEsc;
- clientEdit:
- didPressEsc = editClient(&a[aux.id - 1], aux.id);
- if (didPressEsc == 1)
- break;
- if (saveFile(a, filename) == 1) {
- fileEdited = 1;
- printf("O programa encontrou uma inconveniência com o ID dos clientes e irá resolver o problema!\n");
- break;
- }
- getEdit:
- printf("Deseja alterar mais um campo do cliente %s? <s/n>: ", aux.name);
- switch(tolower(getche())) {
- case 's':
- system("cls");
- goto clientEdit;
- break;
- case 'n':
- break;
- default:
- printf("\nDigite um valor válido!\n");
- goto getEdit;
- break;
- }
- //fileEdited = 1;
- break;
- case '3':
- if (empty_clients(total_clients))
- break;
- printf("Digite o ID do cliente que deseja apagar: ");
- aux = searchClient(a, getNumberFromString(), "", 'i');
- if (deleteClient(&a[aux.id - 1], aux.id) == 0) { // if didn't have errors
- fileEdited = 1;
- }
- break;
- case '4':
- if (empty_clients(total_clients))
- break;
- pesquisaCliente:
- printf("1 - Pesquisa por código (id)\n");
- printf("2 - Pesquisa por nome\n");
- printf("Esc - Voltar\n\n");
- printf("Digite sua opção: ");
- char aux3[30];
- int should_break = 0;
- switch(getche_and_clear()) {
- case 27:
- printf("Operação cancelada!\n");
- should_break = 1;
- break;
- case '1':
- printf("Digite o código do cliente: ");
- aux = searchClient(a, getNumberFromString(), "", 'i');
- break;
- case '2':
- printf("Digite o nome do cliente: ");
- scanf("%[^\n]s", aux3); //gets(aux3); // Was causing minor bugs
- aux3[strlen(aux3)] = '\0';
- fflush(stdin);
- aux = searchClient(a, 0, aux3, 'n');
- break;
- default:
- printf("Opção inválida!\n");
- system("PAUSE");
- system("cls");
- goto pesquisaCliente;
- break;
- }
- if (should_break)
- break;
- if (aux.id != -1)
- printClient(aux);
- else
- printf("Cliente não encontrado.\n");
- break;
- case '5':
- if (empty_clients(total_clients))
- break;
- getOrder:
- printf("Ordenar clientes por:\n");
- printf("1 - ID (código)\n");
- printf("2 - Nome\n");
- printf("3 - Total vendas\n");
- printf("Esc - Voltar\n\n");
- printf("Digite sua opção: ");
- switch(getche_and_clear()) {
- case '1':
- printf("Ordenação por id:\n");
- printAllClients(a, total_clients, 'i');
- break;
- case '2':
- printf("Ordenação por nome:\n");
- printAllClients(a, total_clients, 'n');
- break;
- case '3':
- printf("Ordenação por total de vendas:\n");
- printAllClients(a, total_clients, 't');
- break;
- case 27:
- printf("Operação cancelada!\n");
- break;
- default:
- printf("Digite uma opção válida!\n");
- system("PAUSE");
- system("cls");
- goto getOrder;
- break;
- }
- break;
- default:
- printf("Opção inválida!\n", opcao);
- break;
- }
- if (fileEdited == 1) {
- if (saveFile(a, filename) == 1) {
- goto reProcessClientsArray;
- }
- }
- system("pause");
- system("cls");
- } while(1);
- printf("Encerrando programa...\n");
- saveFile(a, filename);
- printf("Programa finalizado com sucesso!\n");
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement