int main() { setlocale(LC_ALL,"Portuguese"); tpilha *PILHA = (tpilha *) malloc(sizeof(tpilha)); if(!PILHA){ printf("\nSem memoria disponivel!\n"); exit(1); }else{ inicia(PILHA); int opt; tpilha *aux; do{ system("cls"); menu(); scanf("%d",&opt); //opcao(PILHA,opt); switch(opt){ case 0: break; case 1: push(PILHA); break; case 2: aux= pop(PILHA); if(aux != NULL) printf("Retirado: %3d\n\n", aux->num); break; case 3: exibe(PILHA); break; case 4: libera(PILHA); inicia(PILHA); printf("Pilha limpa!\n"); break; } getch(); }while(opt!=0); free(PILHA); return 0; } }
MensagemROS::MensagemROS(const string &msg) { inicia(); bool ok; string strOP = ROSBridgeJSON::JSONextraiCampoSTR(msg,string("op"),&ok); if(!ok) { cout << "Erro ao intepretar msgROS , op nao encontrado" << endl; return; } if(strOP == "publish") { m_tipoMsg = PUBLISHER; m_origem = ROSBridgeJSON::JSONextraiCampoSTR(msg,string("topic")); m_msg = ROSBridgeJSON::JSONextraiCampoJSON(msg,string("msg")); }else if( strOP == "service_response") { m_tipoMsg = SERVICE_RESPONSE; m_origem = ROSBridgeJSON::JSONextraiCampoSTR(msg,string("service")); m_msg = ROSBridgeJSON::JSONextraiCampoJSON(msg,string("values")); }else { cout << "Erro interpretar msg com op " << strOP << endl; } }
void opcao(node *LISTA, int op) { switch(op){ case 0: libera(LISTA); break; case 1: exibe(LISTA); break; case 2: insereInicio(LISTA); break; case 3: insereFim(LISTA); break; case 4: inicia(LISTA); break; default: printf("Comando invalido\n\n"); } }
int main(int argc, char** argv) { int i, j; int rc = 0; char* p; if(argc != 3) { printf("Specify the senders and receivers\n"); exit(EXIT_FAILURE); } errno = 0; N_SENDERS = strtol(argv[1], &p, 10); if(errno != 0 || *p != '\0' || N_SENDERS > INT_MAX) { printf("The number of senders is not valid\n"); exit(EXIT_FAILURE); } errno = 0; N_RECEIVERS = strtol(argv[2], &p, 10); if(errno != 0 || *p != '\0' || N_RECEIVERS > INT_MAX) { printf("The number of receivers is not valid\n"); exit(EXIT_FAILURE); } senders = malloc(N_SENDERS * sizeof(pthread_t*)); receivers = malloc(N_RECEIVERS * sizeof(pthread_t*)); inicia(N_SENDERS, N_RECEIVERS); for(i = 0; i < N_SENDERS; i++) { int* id = malloc(sizeof(*id)); *id = i; rc = pthread_create(&senders[i], NULL, senderThread, (void*) id); checkResults("pthread_create()\n", rc); } for(i = 0; i < N_RECEIVERS; i++) { int* id = malloc(sizeof(*id)); *id = i; rc = pthread_create(&receivers[i], NULL, receiverThread, (void*) id); checkResults("pthread_create()\n", rc); } for(i = 0; i < N_SENDERS; i++) { rc = pthread_join(senders[i], NULL); checkResults("pthread_join()\n", rc); } for(i = 0; i < N_RECEIVERS; i++) { rc = pthread_join(receivers[i], NULL); checkResults("pthread_join()\n", rc); } free(senders); free(receivers); return 0; }
int main() { vet x; int cont1, cont2, cont3, cont4, cont5, cont6, n, i,r; scanf("%d", &n);//Recebe o numero de vezes inicia(&x); srand(time(NULL));//Semente da aleatoriedade for (i = 0; i < n; i++) { r = rand() %6 + 1;//Para ir de 1 a 6 insere (&x, r); } cont1 = verRepeticao (x, 1); cont2 = verRepeticao (x, 2); cont3 = verRepeticao (x, 3); cont4 = verRepeticao (x, 4); cont5 = verRepeticao (x, 5); cont6 = verRepeticao (x, 6); printf("Quantidade de numeros 1: %d\n", cont1); printf("Quantidade de numeros 2: %d\n", cont2); printf("Quantidade de numeros 3: %d\n", cont3); printf("Quantidade de numeros 4: %d\n", cont4); printf("Quantidade de numeros 5: %d\n", cont5); printf("Quantidade de numeros 6: %d\n", cont6); return 0; }
void opcao(node *PRONTOS,node *EXECUTANDO, node *BLOQUEADO,node *FINALIZADOS,int op){ node *tmp; switch(op){ case 0: libera(PRONTOS); break; case 1: libera(PRONTOS); inicia(PRONTOS); break; case 2: listaProcessos(PRONTOS,EXECUTANDO, BLOQUEADO, FINALIZADOS); break; case 3: insere(PRONTOS); break; case 9: Escalonador_Simples(PRONTOS,EXECUTANDO, BLOQUEADO,FINALIZADOS); break; case 4: tmp= retira(PRONTOS); if(tmp != NULL){ printf("Retirado: %3d\n\n", tmp->num); libera(tmp); } break; default: printf("Comando invalido\n\n"); } }
int main(int argc, char** argv) { no *FILA = (no*)malloc(sizeof(no)); inicia(FILA); exibir(FILA); printf("\n"); entraFila(FILA); entraFila(FILA); entraFila(FILA); entraFila(FILA); exibir(FILA); no *temp = movimenta(FILA); printf("\nRetira o %d\n", temp->conteudo); exibir(FILA); temp = movimenta(FILA); printf("\nRetira o %d\n", temp->conteudo); exibir(FILA); temp = movimenta(FILA); printf("\nRetira o %d\n", temp->conteudo); exibir(FILA); temp = movimenta(FILA); printf("\nRetira o %d\n", temp->conteudo); exibir(FILA); movimenta(FILA); free(FILA); return 0; }
int main(){ char *str; str=inicia(); printf("recursivo:"); if(palindromo(str,strlen(str)-1,0)) printf("SIm\n"); else printf("Nao\n"); printf("iterativo:"); if(pal(str)) printf("SIm\n"); else printf("Nao\n"); return 0; }
int main(void){ node *PRONTOS = (node *) malloc(sizeof(node)); node *BLOQUEADO = (node *) malloc(sizeof(node)); node *EXECUTANDO = (node *) malloc(sizeof(node)); node *FINALIZADOS = (node *) malloc(sizeof(node)); inicia(PRONTOS); inicia(BLOQUEADO); inicia(FINALIZADOS); inicia(EXECUTANDO); int opt; do{ opt=menu(); opcao(PRONTOS,EXECUTANDO,BLOQUEADO, FINALIZADOS,opt); } while(opt); free(PRONTOS); return 0; }
void opcao(no *lista, int op){ no *tmp; switch(op){ case 0: libera(lista); printf("Ate mais!\n"); break; case 1: libera(lista); printf("a lista foi limpa!\n"); inicia(lista); break; case 2: printlista(lista); break; case 3: addinicio(lista); break; case 4: addfim(lista); break; case 5: colocaqualquer(lista); break; case 6: tmp= removecomeco(lista); break; case 7: tmp= removefim(lista); break; case 8: tmp= excluialguem(lista); break; case 9: printf("\nValor a ser procurado: "); scanf("%d",&valor); procuralista(lista,valor); break; default: printf("Comando invalido\n\n"); } }
int main() { int x, i; vet v; inicia(&v); for (i = 0; i < 20; i++) insere(&v, i); while(!vazio(v)) { retira(&v, &x); if (x > 10) printf("%d ", x); } return 0; }
/** \param nivel \return **/ QString BcPlanContableArbol::codigoCuentaMayor ( unsigned int nivel ) { BL_FUNC_DEBUG QString codigo; inicia(); while ( deshoja ( nivel, true ) ); codigo = hojaActual ( "codigo" ); return codigo; }
/** \param codigo \param nivel \return **/ bool BcPlanContableArbol::irHoja ( QString codigo, unsigned int nivel ) { BL_FUNC_DEBUG inicia(); while ( deshoja ( nivel, true ) && hojaActual ( "codigo" ) != codigo ); if ( hojaActual ( "codigo" ) == codigo ) { return true; } else { return false; } // end if }
int main(){// Função principal No *Fila = (No *) malloc(sizeof(No)); if(Fila== NULL){ printf("Sem memoria disponivel para alocar a Fila.\n"); exit(1); } else{ inicia(Fila); menu(Fila); free(Fila); return 0; } }
/** \param cuenta \param nivel \return **/ QString BcPlanContableArbol::hijoMayor ( QString cuenta, unsigned int nivel ) { BL_FUNC_DEBUG QString codigohoja, codigohijo = cuenta; inicia(); while ( deshoja ( nivel, true ) ) { codigohoja = hojaActual ( "codigo" ); if ( codigohoja.startsWith ( cuenta ) && codigohoja.length() >= codigohijo.length() ) codigohijo = codigohoja; } return codigohijo; }
int main(void) { node *LISTA = (node *) malloc(sizeof(node)); if(!LISTA){ printf("Sem memoria disponivel!\n"); exit(1); } inicia(LISTA); int opt; do{ opt=menu(); opcao(LISTA,opt); }while(opt); free(LISTA); return 0; }
int main(void){ no *lista = (no *) malloc(sizeof(no)); if(!lista){ printf("Sem memoria disponivel!\n"); exit(1); }else{ inicia(lista); int opt; do{ opt=menu(); opcao(lista,opt); }while(opt); free(lista); return 0; } }
int loop(){ //inicia a pilha usada pelo programa pilha *p = inicia(); char g_char[MAX_LENTH]; //exibe o cabeçalho do programa if(!RUN_CODES) exibeHeader(); //loop principal while(1){ gets(g_char); if(strlen(g_char) > 1) tiraEspaco(g_char); //define a saida do programa char sair_s[] = "s"; char sair_S[] = "S"; if(!strcmp(g_char, sair_S) || !strcmp(g_char, sair_s)) return 1; //define a entrada em help char help_h[] = "h"; char help_H[] = "H"; if(!strcmp(g_char, help_h) || !strcmp(g_char, help_H)){ if(!RUN_CODES) exibeHelp(); fflush(stdin); continue; } //entra na função que trata cada char da string informada pelo usuario int erro = calcular(g_char, p); if(erro == 1){ if(!RUN_CODES){ exibeHeader(); printf("\nErro! Para fazer um calculo, inicie com E\n"); } } } return 1; }
int main(int argc, char *argv[]) { unsigned short int c; inicia(); imprime(); while(1) { if(kbhit()) { c = getch(); mover(c); } if(z % 4681 == 0) { print(x, y, ((z % 9362 == 0) ? (s ? blink : unblink) : m[t[x][y]])); } z++; } getch(); return 1; }
int main(){ int opcao; List *list = (List*)malloc(sizeof(List)); inicia(list); do{ menu_opcao(); scanf("%d", &opcao); switch(opcao){ case 1: break; case 2: break; case 3: break; } }while(opcao != 6); system("pause"); return 0; }
void main() { inicia(); menuprincipal(); }
void* create2(void *f, Tipo ret, unsigned n, Parametro *params){ int i,j,k=0; char *v = (char*)malloc(1024); k = inicia(k,v); printf("k = %d\n",k); printf("ant for\n"); int desl = ultParam(params,n); printf("desl = %d\n", desl); for(i=n-1;i>=0;i--){ printf("dentro for\n"); // AMARAÇÃO LIVRE if(params[i].amarracao == 0){ printf("AMARAÇÃO LIVRE\n"); //DOUBLE if(params[i].tipo == 4){ printf("DOUBLE\n"); printf("desl = %d\n", desl); // CHAMAR livreConstDouble(); k = livreDouble(k,v,desl); desl-=4; } // VOID , INT , CHAR , FLOAT e POINTER else if((params[i].tipo>=0 && params[i].tipo<=3) || (params[i].tipo==5)){ printf("NOT DOUBLE\n"); printf("desl = %d\n", desl); // CHAMAR livreNotDouble(); k = livreNotDouble(k,v,desl); } else{ printf("DEU PAU 1\n"); } } // AMARAÇÃO CONSTANTE else if(params[i].amarracao == 1){ printf("AMARAÇÃO CONSTANTE\n"); //DOUBLE if(params[i].tipo == 4){ printf("DOUBLE\n"); printf("desl = %d\n", desl); // CHAMAR livreConstDouble(); k = constDouble(k,v,desl,params[i].valor.vDouble); } // VOID , INT , CHAR , FLOAT e POINTER else if((params[i].tipo>=0 && params[i].tipo<=3) || (params[i].tipo==5)){ printf("NOT DOUBLE \n"); printf("desl = %d\n", desl); // CHAMAR constNotDouble(); //v[k] = descobrevalor(params[i]); // push valor if(params[i].tipo == CHAR){ v[k] = params[i].valor.vChar; } else if(params[i].tipo == FLOAT){ v[k] = params[i].valor.vFloat; } else if(params[i].tipo == INT){ v[k] = params[i].valor.vInt; } else if(params[i].tipo == DOUBLE){ v[k] = params[i].valor.vDouble; } else if(params[i].tipo == POINTER){ //v[k] = params[i].valor.vPointer; } else printf("DEU PAU\n"); //k++; } else printf("DEU PAU 2\n"); } // AMARAÇÃO FUNÇÃO else if(params[i].amarracao == 2){ //DOUBLE if(params[i].tipo == 4){ //v[k]= ;//asdas //k++; } // VOID , INT , CHAR , FLOAT e POINTER else if((params[i].tipo>=0 && params[i].tipo<=3) || (params[i].tipo==5)){ } else printf("DEU PAU 3\n"); } else printf("DEU PAU 4\n"); if(params[i].amarracao != 1){ desl-=4; } } k=callEnd(f,v,k); printf("FINAL create\n"); return v; }
int main(void){ Categoria *listCat=(Categoria*)malloc(sizeof(Categoria)); if(!listCat) { printf("Sem memoria disponivel!\n"); //Provocando uma saída do sistema caso a memória que precisemos não seja alocada. exit(1); } inicia(listCat); int quant=0; int op; do{ printf("\nMenu\n\n"); printf("1) Cadastrar categoria.\n"); printf("2) Cadastro da lista de Produtos.\n"); printf("3) Listar as categorias.\n"); printf("4) Buscar uma categoria por ID.\n"); printf("0) Sair do programa.\n"); printf(" >"); scanf("%d", &op); switch(op){ case 1: cadListCategoria(listCat,&quant); /*if(listProd!=NULL) free(listProd); listProd = totalProdutos(&quant);*/ system("cls"); break; case 2: cadListProdutoCat(listCat); //system("cls"); break; case 3: listarCategorias(listCat,quant); break; case 4: mostraCatID(listCat); break; case 0: break; default: break; } } while(op!=0); //DESALOCA TODOS AS CATEGORIAS E PRODUTOS libera(listCat); //LIBERA A PRÓPRIA LISTA printf("Liberando a lista\n\n"); // free(listCat); system("pause"); return EXIT_SUCCESS; }
int main(int player, int n, int dificuldade) { char tela[ALTURA][LARGURA]; Bola b; Raquete r1, r2; int dir, pause = 0; Score s; int i, j; if (n != 1) { inicia(tela, &b, &r1, &r2, &s, 0); } else if (player == 2 && dificuldade == 0) { inicia(tela, &b, &r1, &r2, &s, player); while (1) { COORD cord; cord.X = 0; cord.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord); desenha_tela(tela, &r1, &r2, &s); if (_kbhit()) { dir = _getch(); while (dir == 'p' && pause == 0) { pause(); SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord); desenha_tela(tela, &r1, &r2, &s); dir = _getch(); if (dir == 'p') { unpause(); pause++; } else { dir = 'p'; } } pause = 0; dirRaquetes(tela, &r1, dir, &r2); } move_ball(tela, &b, &r1, &r2, &s); } return 0; } else if (player == 1 && (dificuldade == 1 || dificuldade == 2)) { inicia(tela, &b, &r1, &r2, &s, player); while (1) { COORD cord; cord.X = 0; cord.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord); desenha_tela(tela, &r1, &r2, &s); if (_kbhit()) { dir = _getch(); while (dir == 'p' && pause == 0) { pause(); SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord); desenha_tela(tela, &r1, &r2, &s); dir = _getch(); if (dir == 'p') { unpause(); pause++; } else { dir = 'p'; } } pause = 0; dirRaquetes_1Player(tela, &r1, dir); } move_ball(tela, &b, &r1, &r2, &s); move_raquetePC(tela, &b, &r2, &r1, dificuldade); } return 0; } else if (player == 3 && dificuldade == 0) { inicia(tela, &b, &r1, &r2, &s, player); while (1) { COORD cord; cord.X = 0; cord.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord); desenha_tela(tela, &r1, &r2, &s); if (_kbhit()) { dir = _getch(); if (dir == ESC) { exit(0); } while (dir == 'p' && pause == 0) { pause(); SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord); desenha_tela(tela, &r1, &r2, &s); dir = _getch(); if (dir == 'p') { unpause(); pause++; } else { dir = 'p'; } } pause = 0; } move_ball(tela, &b, &r1, &r2, &s); move_raquetePC(tela, &b, &r2, &r1, dificuldade); } return 0; } }
/** * Função principal * * @param argc * @param argv * @return */ int main(int argc, char *argv[]) { char nome[20], operacao; int idade, chave; // Criação de lista de reinserção de elementos node *LISTA = (node *) malloc(sizeof (node)); if (!LISTA) { // fprintf(stderr, "memória insuficiente para criar lista \n"); } else { inicia(LISTA); } // Criação de arquivo if ((arquivo_hashing = fopen(ARQUIVO, "rb")) == NULL) { // inicializa tabela hash inicializar(); // cria arquivo para inserção da tabela hash criar_arquivo(); } // Verifica qual operação será executada scanf("%c", &operacao); do { switch (operacao) { case 'i': scanf("%d", &chave); // scanf lendo string com espaços em branco scanf(" %[^\n]s", &nome); // fflush(stdin); scanf("%d", &idade); inserir_chave(chave, nome, idade); break; case 'c': // fprintf(stderr, "CONSULTAR\n"); scanf("%d", &chave); consultar(chave, 0); break; case 'r': // fprintf(stderr, "REMOVER\n"); scanf("%d", &chave); int result = consultar(chave, 1); if (result != -1) { // fprintf(stderr, "indíce para remover: %d\n", result); // remoção remover(chave); } else { fprintf(stderr, "chave nao encontrada: %d", chave); } break; case 'p': // fprintf(stderr, "IMPRIMIR\n"); imprimir(); break; case 'm': // fprintf(stderr, "MEDIA DE ACESSOS\n"); media_acessos(); break; case 'e': return 0; break; //exit default: break; } // limpa caracter do buffer antes do próximo loop operacao = getchar(); } while (operacao != 'e'); // fclose(arquivo_hashing); return 0; }
/** * Remove chave * @param chave a ser removida * @return */ void remover(int chave) { int salto, index_aux, pai_index; registro cleaner; cleaner.apontador = -1; cleaner.chave = -1; cleaner.idade = -1; cleaner.index_father = -1; strcpy(cleaner.nome, ""); // inicializa lista node *LISTA = (node *) malloc(sizeof (node)); if (!LISTA) { // fprintf(stderr, "Sem memória disponivel!\n"); exit(1); } else { inicia(LISTA); } // arquivo binário if ((arquivo_hashing = fopen(ARQUIVO, "rb+")) == NULL) { // fprintf(stderr, "\nErro ao abrir arquivo!"); // printf("\nErro ao abrir arquivo!"); return; } // consultar índice a ser removido int indice_remove = consultar(chave, 1); // pode ser 0 até TAMANHO_ARQUIVO if (indice_remove != -1) { // lê o registro da posição a ser removido fseek(arquivo_hashing, ((indice_remove + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); // verifica se corresponde a chave a ser removida if (tabela_h.chave == chave) { // salva índice para pai pai_index = tabela_h.index_father; // salva índice original index_aux = indice_remove; salto = h2(tabela_h.chave) * tabela_h.apontador + index_aux; if (salto >= TAMANHO_ARQUIVO) salto -= TAMANHO_ARQUIVO; while (tabela_h.apontador != -1) { fseek(arquivo_hashing, ((salto + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); insereFim(LISTA, tabela_h.chave, tabela_h.nome, tabela_h.idade); index_aux = salto; salto = h2(tabela_h.chave) * tabela_h.apontador + salto; if (salto >= TAMANHO_ARQUIVO) salto -= TAMANHO_ARQUIVO; // limpa_registro(index_aux); remove_registro(index_aux); } // remove índice // limpa_registro(indice_remove); remove_registro(indice_remove); limpa_apontador_pai(pai_index); reinsere_lista(LISTA); } } }
/** * Calcula média de acessos as chaves inseridas */ void media_acessos() { float count_jumps = 0, qtd_chaves = 0; // int count_jumps = 0, qtd_chaves = 0; node *LISTA = (node *) malloc(sizeof (node)); if (!LISTA) { exit(1); } else { inicia(LISTA); } if ((arquivo_hashing = fopen(ARQUIVO, "rb+")) == NULL) { printf("\nErro ao abrir arquivo!"); return; } // int i; // contar as chaves inseridas, salvar em uma lista e consultar até o final da lista for (int i = 0; i < TAMANHO_ARQUIVO; i++) { fseek(arquivo_hashing, ((i + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); // insere todas as chaves do arquivo na lista if (tabela_h.chave != -1) { insereFim(LISTA, tabela_h.chave, tabela_h.nome, tabela_h.idade); qtd_chaves++; } } if (vazia(LISTA)) { // return; } node *tmp; tmp = LISTA->prox; //loop para contar os acessos while (tmp != NULL) { int indice_elemento = consultar(tmp->chave, 1); int exit = 0; // retirar depois // printf("Chave: %d %s %d\n", tmp->chave, tmp->nome, tmp->idade); // consultar todos os pais while (exit == 0) { fseek(arquivo_hashing, (indice_elemento + 1) * sizeof (struct REGISTRO), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); // fprintf(stderr, "jumps %f\n", count_jumps); //saída do loop dos pais if (tabela_h.index_father == -1) { exit = 1; // fprintf(stderr, "cj %d", count_jumps); } else indice_elemento = tabela_h.index_father; // incrementa contador count_jumps++; } // seleciona próximo da lista tmp = tmp->prox; } if (qtd_chaves != 0) { float media_acessos = count_jumps / qtd_chaves; fprintf(stderr, "%.1f", media_acessos); } else { fprintf(stderr, "0.0"); } // media = acessos / TAMANHO_ARQUIVO fclose(arquivo_hashing); }
/** * Inserir registro na tabela hash * @param nome * @param idade * @param chave */ void inserir_chave(int chave, char nome[20], int idade) { int aux, indice = 0, salto, count_jumps = 0, go_to_index, index_aux, index_before_jump; registro register_aux, register_jump; indice = (int) h1(chave); // se já não existir, insere // if (!check_key(chave)) { // não existe if (consultar(chave, 1) == -1) { register_aux.chave = chave; strcpy(register_aux.nome, nome); register_aux.index_father = -1; register_aux.idade = idade; register_aux.apontador = -1; if ((arquivo_hashing = fopen(ARQUIVO, "rb+")) == NULL) { printf("\nErro ao abrir arquivo!"); return; } rewind(arquivo_hashing); fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); // SEM colisão if (tabela_h.chave == -1) { fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); }// else { // verificar se o que está na posição está no seu home adress if (h1(tabela_h.chave) == indice) { // está no homeAdress if (tabela_h.apontador == -1) { //NÃO tem sucessor. Salta para o sucessor salto = h2(tabela_h.chave); fseek(arquivo_hashing, ((salto + indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); index_aux = indice; //salva o índice atual // CASO BASE if (tabela_jump.chave == -1) { // salva o novo registro fseek(arquivo_hashing, ((salto + indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); // salva o indice do pai register_aux.index_father = indice; fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); // lê registro para salvar apontador para sucessor fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); count_jumps++; tabela_h.apontador = count_jumps; // salva apontador para sucessor fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fwrite(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); } // posição ocupada - pular de h2 em h2 até achar uma disponível if (tabela_jump.chave != -1) { // index_aux++; go_to_index = salto + index_aux; // loop de busca de posição vazia do { fseek(arquivo_hashing, ((go_to_index + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); count_jumps++; if (tabela_jump.chave != -1) { // posição ocupada, procurar nova posição // count_jumps++; //acerta apontador de saltos do home adress // index_aux++; index_aux = go_to_index + salto; // go_to_index = salto + index_aux; go_to_index = go_to_index + salto; if (go_to_index >= TAMANHO_ARQUIVO) go_to_index -= TAMANHO_ARQUIVO; } else { // salva o registro fseek(arquivo_hashing, ((go_to_index + 1) * sizeof (struct REGISTRO)), SEEK_SET); // salva o indice do pai register_aux.index_father = indice; fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); // acertando o apontador de sucessores tabela_h.apontador = count_jumps; //acerta o apontador de saltos fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fwrite(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); } } while (tabela_jump.chave != -1 && go_to_index != indice); } } else { // TEM SUCESSORE(S). É uma cadeia salto = (h2(tabela_h.chave) * tabela_h.apontador) + indice; if (salto >= TAMANHO_ARQUIVO) salto -= TAMANHO_ARQUIVO; // guarda o indice atual para saber onde acertar o apontador int new_index = salto; fseek(arquivo_hashing, ((salto + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); count_jumps++; while (tabela_jump.apontador != -1 && new_index != indice) { salto = (h2(tabela_jump.chave) * tabela_jump.apontador) + new_index; if (salto >= TAMANHO_ARQUIVO) salto -= TAMANHO_ARQUIVO; new_index = salto; // salva o índice anterior ao salto index_before_jump = new_index; count_jumps++; //salva o número de saltos p/ register_aux fseek(arquivo_hashing, ((new_index + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); } // saiu pq achou o último da cadeia if (new_index != indice) { // salta pelo h2 até achar uma vaga ou terminar o arquivo index_before_jump = new_index; // salva o índice a ser atualizado salto = h2(tabela_jump.chave) + new_index; int index_h2 = h2(tabela_jump.chave); do { fseek(arquivo_hashing, ((salto + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); if (tabela_jump.chave == -1) { fseek(arquivo_hashing, ((salto + 1) * sizeof (struct REGISTRO)), SEEK_SET); // salva o indice do pai register_aux.index_father = index_before_jump; // register_aux.index_father = indice; fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); // acertar o apontador fseek(arquivo_hashing, ((index_before_jump + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); tabela_jump.apontador = count_jumps; // salva saltos para pai fseek(arquivo_hashing, ((index_before_jump + 1) * sizeof (struct REGISTRO)), SEEK_SET); fwrite(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); register_aux = tabela_jump; fseek(arquivo_hashing, ((index_before_jump + 1) * sizeof (struct REGISTRO)), SEEK_SET); // fwrite(&tabela_jump, sizeof (struct REGISTRO), 1, arquivo_hashing); fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); // fclose(arquivo_hashing); // previnir loop infinito return; } else { // saltando de h2 em h2 até encontrar uma posição new_index = salto; salto += index_h2; if (salto >= TAMANHO_ARQUIVO) salto -= TAMANHO_ARQUIVO; } count_jumps++; } while (tabela_jump.apontador != -1 || salto != indice); } } }// NÃO ESTÁ NO HOME ADRESS else { // retira ele e os seus sucessores e os reinsere int pai = tabela_h.index_father; // inicializa lista node *LISTA = (node *) malloc(sizeof (node)); if (!LISTA) { // fprintf(stderr, "Sem memória disponivel!\n"); exit(1); } else { inicia(LISTA); } // NÃO TEM SUCESSORES - APENAS 1 A SER REINSERIDO if (tabela_h.apontador == -1) { int key = tabela_h.chave, age = tabela_h.idade; char name[20]; strcpy(name, tabela_h.nome); // salva na lista para reinserção insereFim(LISTA, tabela_h.chave, tabela_h.nome, tabela_h.idade); // insere no lugar deste o registro fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); fclose(arquivo_hashing); // ACERTA APONTADOR DO PAI limpa_apontador_pai(pai); // reinsere o elemento reinserir_chave(key, name, age); // REINICIA A LISTA inicia(LISTA); return; }// tem que reinserir todos até o final da cadeia else { int jump_to; // LOOP até encontrar o final da cadeia while (tabela_h.apontador != -1) { // salva na lista para reinserção insereFim(LISTA, tabela_h.chave, tabela_h.nome, tabela_h.idade); // calcula salto para o próximo para inserir jump_to = (h2(tabela_h.chave) * tabela_h.apontador) + indice; if (jump_to >= TAMANHO_ARQUIVO) jump_to -= TAMANHO_ARQUIVO; // MARCAR POSIÇÃO COMO VÁLIDA limpa_registro(indice); // lê o próximo da cadeia fseek(arquivo_hashing, ((jump_to + 1) * sizeof (struct REGISTRO)), SEEK_SET); fread(&tabela_h, sizeof (struct REGISTRO), 1, arquivo_hashing); } // insere o último da cadeia insereFim(LISTA, tabela_h.chave, tabela_h.nome, tabela_h.idade); // MARCAR POSIÇÃO COMO VÁLIDA limpa_registro(jump_to); // após inserir antigos na lista, insere novo fseek(arquivo_hashing, ((indice + 1) * sizeof (struct REGISTRO)), SEEK_SET); fwrite(®ister_aux, sizeof (struct REGISTRO), 1, arquivo_hashing); fclose(arquivo_hashing); // ACERTA APONTADOR DO PAI limpa_apontador_pai(pai); //reinsere os da lista reinsere_lista(LISTA); // reinicia a lista inicia(LISTA); } // exibe(LISTA); } } fclose(arquivo_hashing); } else { fprintf(stderr, "Chave ja existente\n"); } // imprimir() }
MensagemROS::MensagemROS() { inicia(); }
int main(int argc, char** argv) { ptdia p; inicia(&p); inseredia(&p); return (EXIT_SUCCESS); }