void criar(){ if ((fcliente = fopen("clientes.dat","a")) == NULL){ clrscr(); linha(1); linha(3); center("Erro de Cria‡Æo de Arquivo", 2); return;} fclose(fcliente);}
void tabuada_n(int n){ int i=0; for(i=1; i<=10;i++){ printf("\n"); linha(n,i); } }
int main(int argc, char *argv[]) { const int TAM = 10; int i, soma; int valores[TAM]; soma = 0; for(i = 0; i <TAM; i++) { printf("\nDigite um valor: "); scanf("%d", &valores[i]); } for(i = 0; i<TAM; i++) { soma += valores[i]; } printf("\nA media e %.2f \n", soma/(TAM*1.0)); for(i = 0; i <TAM; i++) { printf("\n%d\t", valores[i]); linha(valores[i]); } printf("\n"); system("PAUSE"); return 0; }
void menu(){ char op; clrscr(); linha(1); linha(3); center("Menu Principal",2); gotoxy(30,5); cout<<"1 ... Cadastro"; gotoxy(30,7); cout<<"2 ... Listar"; gotoxy(30,9); cout<<"3 ... Fim do Programa"; linha(22); linha(24); center("Escolha a Op‡Æo: ", 23); cin>>op; switch (op){ case '1': cadastrar(); break; case '2': listar(); break; case '3': exit(0); break; default : menu();}}
void listar(){ char op; clrscr(); linha(1); linha(3); center("Listagem",2); fcliente = fopen("clientes.dat","r"); rewind(fcliente); do{ fread(&cliente, sizeof(cliente),1,fcliente); gotoxy(3,6); clreol(); cout<<"Cliente: "<<cliente.nome; gotoxy(3,7); clreol(); cout<<"Endere‡o: "<<cliente.endereco; gotoxy(3,8); clreol(); cout<<"Idade: "<<cliente.idade; linha(22); linha(24); center("<P> para Ver o Pr¢ximo Cadastro :: <M> para Voltar ao Menu Principal",23); op = getch(); op = toupper(op);} while(!feof(fcliente) || (op == 'M')); fclose(fcliente); linha(22); linha(24); gotoxy(1,23); clreol(); center("Pressione Alguma Tecla para Voltar ao Menu Principal",23); getch(); menu();}
/*Verifica numero a numero se eh zero*/ void verifica(int ma[][]) { int m , k; for (m=0;m<9;m++) { for(k=0;k<9;k++) { if(ma[m][k] == 0) { linha(ma[m][k],i,j); } } } }
static int regspritelineshot (lua_State *L) { Shot* w = (Shot*)lua_touserdata(L, 1); Ponto a,b; a.x = lua_tonumber(L, 2); a.y = lua_tonumber(L, 3); b.x = lua_tonumber(L, 4); b.y = lua_tonumber(L, 5); Linha linha(a,b); linha.color[0] = lua_tonumber(L, 6); linha.color[1] = lua_tonumber(L, 7); linha.color[2] = lua_tonumber(L, 8); w->sprite.addLinha(linha); return 0; }
void cadastrar(){ char op; int tamanho; clrscr(); linha(1); linha(3); center("Cadastro",2); fcliente = fopen("clientes.dat","r+"); rewind (fcliente);// rewind aponta para a primeira posi‡Æo do{ fread(& cliente, sizeof(cliente),1,fcliente); tamanho++;} while (!feof(fcliente)); fseek(fcliente,sizeof(cliente), tamanho); // fseek aponta para a posi‡Æo tamanho do arquivo cliente do { gotoxy(3,5); clreol(); cout<<"Nome do Cliente: "; cin>>cliente.nome; /* gets lˆ apenas string que ‚ um conjunto de char getch lˆ apenas um caractere ambos nƒo mostram no v¡deo o que foi digitado, getche grava um caracter e mostra no v¡deo */ gotoxy(3,6); clreol(); cout<<"Endere‡o do Cliente: "; cin>>cliente.endereco; gotoxy(3,7); clreol(); cout<<"Idade do Cliente: "; cin>>cliente.idade; // comandos de entrada em c++ sÆo substitu¡dos por cin<< // comandos de sa¡da sÆo substitu¡dos por cout<< tamanho = tamanho + fwrite(& cliente, sizeof(cliente),1,fcliente); linha(22); linha(24); center("Deseja Cadastrar Novamente <S/N>", 23); cin>>"op"; op = toupper(op);} while (op == 'N'); fclose(fcliente); linha(22); linha(24); center("Pressione Alguma Tecla para Voltar ao Menu Principal",23); getch(); menu();}
int main(int argc, char** argv){ char x0[50], x1[50], x2[50], x3[50], x4[50], y0[50], y1[50], y2[50], y3[50], y4[50]; int retorno = 0, pos; char cmd; comando = (char*) malloc(sizeof(char)*BUFSIZE); serial_fd = abrir_porta(); if(serial_fd == -1) { printf("Erro abrindo a porta serial /dev/ttyS0\nAbortando o programa..."); return -1; } else { if(configurar_porta(serial_fd) == -1){ printf("Erro inicializando a porta\n"); close(serial_fd); return -1; } Mat image; image= imread("branco.png",CV_LOAD_IMAGE_GRAYSCALE); if(!image.data) printf("Não foi possível carregar a imagem\n"); namedWindow("janela",WINDOW_AUTOSIZE); pos = theta[0]*2000/180 + 500; retorno = enviarComando(BAS_SERVO,pos); pos = theta[1]*2000/180 + 500; retorno = enviarComando(SHL_SERVO,pos); pos = theta[2]*2000/180 + 500; retorno = enviarComando(ELB_SERVO,pos); pos = theta[3]*2000/180 + 500; retorno = enviarComando(WRI_SERVO,pos); pos = 500; retorno = enviarComando(GRI_SERVO,pos); while(terminar != -1){ // PRIMEIRO COMANDO - POSICAL INICIAL printf("\n\n\nESCOLHA ENTRE AS OPCOES DE MOVIMENTO\n"); printf("a - INCREMENTAR BASE\n"); printf("z - DECREMENTAR BASE\n"); printf("s - IMCREMENTAR OMBRO\n"); printf("x - DECREMENTAR OMBRO\n"); printf("d - IMCREMENTAR COTOVELO\n"); printf("c - DECREMENTAR COTOVELO\n"); printf("f - INCREMENTAR PUNHO\n"); printf("v - DECREMENTAR PUNHO\n"); printf("g - ABRIR GARRA\n"); printf("b - FECHAR GARRA\n"); printf("1 - SALVAR VALOR 1\n"); printf("2 - SALVAR VALOR 2\n"); printf("3 - SALVAR VALOR 3\n"); printf("4 - SALVAR VALOR 4\n"); printf("5 - SALVAR VALOR 5\n"); printf("p - CRIAR IMAGEM\n"); printf("l - FINALIZAR APLICACAO\n \n"); retorno = system("/bin/stty raw"); cmd = getchar(); retorno = system("/bin/stty cooked"); if(retorno == -1) break; switch(cmd){ case 'a': if(theta[0] < 180) theta[0] = theta[0] + 1; pos = theta[0]*2000/180 + 500; retorno = enviarComando(BAS_SERVO,pos); break; case 'z': if(theta[0] > 0) theta[0] = theta[0] - 1; pos = theta[0]*2000/180 + 500; retorno = enviarComando(BAS_SERVO,pos); break; case 's': if(theta[1] < 180) theta[1] = theta[1] + 1; pos = theta[1]*2000/180 + 500; retorno = enviarComando(SHL_SERVO,pos); break; case 'x': if(theta[1] > 0) theta[1] = theta[1] - 1; pos = theta[1]*2000/180 + 500; retorno = enviarComando(SHL_SERVO,pos); break; case 'c': if(theta[2] < 180) theta[2] = theta[2] + 1; pos = theta[2]*2000/180 + 500; retorno = enviarComando(ELB_SERVO,pos); break; case 'd': if(theta[2] > 0) theta[2] = theta[2] - 1; pos = theta[2]*2000/180 + 500; retorno = enviarComando(ELB_SERVO,pos); break; case 'f': if(theta[3] < 180) theta[3] = theta[3] + 1; pos = theta[3]*2000/180 + 500; retorno = enviarComando(WRI_SERVO,pos); break; case 'v': if(theta[3] > 0) theta[3] = theta[3] - 1; pos = theta[3]*2000/180 + 500; retorno = enviarComando(WRI_SERVO,pos); break; case 'g': theta[4] = 0; pos = 1500; retorno = enviarComando(GRI_SERVO,pos); break; case 'b': theta[4] = 1; pos = 2400; retorno = enviarComando(GRI_SERVO,pos); break; case 'l': terminar = -1; break; case '1': definirPosicao(0); printf("\nX[0]: %.1f Y[0]: %.1f", x[0], y[0]); break; case '2': definirPosicao(1); printf("\nX[1]: %.1f Y[1]: %.1f", x[1], y[1]); break; case '3': definirPosicao(2); printf("\nX[2]: %.1f Y[2]: %.1f", x[2], y[2]); break; case '4': definirPosicao(3); printf("\nX[3]: %.1f Y[3]: %.1f", x[3], y[3]); break; case '5': definirPosicao(4); printf("\nX[4]: %.1f Y[4]: %.1f", x[4], y[4]); break; case 'p': x[0] *= 50; x[1] *= 50; x[2] *= 50; x[3] *= 50; x[4] *= 50; y[0] *= 50; y[1] *= 50; y[2] *= 50; y[3] *= 50; y[4] *= 50; int xInt[5], yInt[5]; xInt = x[0]; yInt = y[0]; xInt = x[1]; yInt = y[1]; xInt = x[2]; yInt = y[2]; xInt = x[3]; yInt = y[3]; xInt = x[4]; yInt = y[4]; linha(xInt[0], yInt[0], xInt[1], yInt[1], image); //Ponto 1 -> Ponto 2 linha(xInt[0], yInt[0], xInt[2], yInt[2], image); //Ponto 1 -> Ponto 3 linha(xInt[1], yInt[1], xInt[2], yInt[2], image); //Ponto 2 -> Ponto 3 linha(xInt[1], yInt[1], xInt[3], yInt[3], image); //Ponto 2 -> Ponto 4 linha(xInt[2], yInt[2], xInt[4], yInt[4], image); //Ponto 3 -> Ponto 5 linha(xInt[3], yInt[3], xInt[4], yInt[4], image); //Ponto 4 -> Ponto 5 imshow("janela", image); waitKey(); break; default: printf("\nOPÇÃO INVALIDA\n"); break; } if(retorno == -1) break; } fechar_porta(serial_fd); printf("\nPROGRAMA FINALIZADO\n"); } return 0; }
void main() { int modo=DETECT,drive,resp; initgraph(&modo,&drive,"c:\\bc\\bgi"); inicio: setcolor(4); setfillstyle( SOLID_FILL,4); resp=linha(247,179,432,320,4); if(resp==1) goto inicio; for(i=6.8;i>6.4;i-=0.005) { col=cos(i)*160 + 320; lin=sin(i)*160 + 170; setcolor(4); cardio(col,lin,4); cardio(640-col,lin,4); setcolor(0); cardio2(col,lin,4); cardio2(col,lin,5); cardio2(col,lin,6); cardio2(col,lin,7); cardio2(640-col,lin,4); cardio2(640-col,lin,5); cardio2(640-col,lin,6); cardio2(640-col,lin,7); delay(1); if(num>9 && num<13) if(i<mt[num]) { num++; goto inicio; } } for(i=6.5;i>3.2;i-=0.005) { col=cos(i)*80 + 400; lin=sin(i)*80 + 170; setcolor(4); cardio(col,lin,4); cardio(640-col,lin,4); setcolor(0); cardio2(col,lin,4); cardio2(col,lin,5); cardio2(col,lin,6); cardio2(col,lin,7); cardio2(640-col,lin,4); cardio2(640-col,lin,5); cardio2(640-col,lin,6); cardio2(640-col,lin,7); delay(1); if(num<10) if(i<mt[num]) { num++; goto inicio; } } cleardevice(); setcolor(4); cardio(320,165,4); for(i=650;i>25;i--) { setcolor(4); outtextxy(i,200,"No final, Dois coracoes apaixonados sempre se encontram em um so coracao. "); delay(50); setcolor(0); outtextxy(i,200,"No final, Dois coracoes apaixonados sempre se encontram em um so coracao. "); } setcolor(4); outtextxy(i,200,"No final, Dois coracoes apaixonados sempre se encontram em um so coracao. "); getch(); }
int main( int argc , char *argv[]) { signal(SIGINT, ctrlHandler); n_linhas = linhas("localdns.txt"); #ifdef DEBUG printf("Verificacao dos ficheiros presentes.\n"); #endif if(verifica_ficheiros("localdns.txt") == 0) { printf("Ficheiro localdns.txt inexistente!\n"); exit(1); } if(verifica_ficheiros("config.txt") == 0) { printf("Ficheiro config.txt inexistente!\n"); exit(1); } #ifdef DEBUG printf("Inicializacoes.\n"); #endif unsigned char buf[65536], *reader, *reader2, qname; int sockfd, stop; struct DNS_HEADER *dns = NULL; struct stats stat; struct sockaddr_in servaddr, dest; socklen_t len; int i, np, r; cfg_process = 1; stats_process = 1; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); #ifdef DEBUG printf("Criacao das Filas Normal e Prioridade e da lista de Domains locais.\n"); #endif Fila fila_normal = cria_fila(); Fila fila_prioridade = cria_fila(); Local l_domains = cria_lista(); // Hora de arranque do Servidor time_t clk = time(NULL); strcpy(stat.data_hora_arranque, ctime(&clk)); // Inicializaco Memoria Partilhada init_shm(); ptr_config->flag = 0; printf("[PAI - MAIN] PID Main = %d PID DO MEU PAI = %d\n", getpid(), getppid()); char* data; #ifdef DEBUG printf("Criacao processo de configuracoes.\n"); #endif if ((cfg_process = fork()) == 0) { signal(SIGUSR1, handler_CFG); #ifdef DEBUG printf("RELEASE CFG.\n"); printf("Mapeamento de localdns.txt.\n"); #endif mapear("localdns.txt"); #ifdef DEBUG printf("Leitura de config.txt para estrutura em memoria partilhada.\n"); #endif file2memory("config.txt"); if(signal(SIGALRM, SIG_IGN) == SIG_ERR) { perror("SIGALRM Ignore error"); exit(1); } } else { usleep(200000); if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("Signal ignore error"); exit(1); } #ifdef DEBUG printf("RELEASE MAIN.\n"); #endif #ifdef DEBUG printf("Extrair enderecos e ip's locais do mmap\n"); #endif token_mmap(l_domains, ptr_config->data); // Check arguments if(argc <= 1) { printf("Usage: %s <port>\n", argv[0]); exit(1); } // Get server UDP port number int port = atoi(argv[1]); if(port <= 0) { printf("Usage: %s <port>\n", argv[0]); exit(1); } // **************************************** // Create socket & bind // **************************************** // Create UDP socket sockfd = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP); //UDP packet for DNS queries if (sockfd < 0) { printf("ERROR opening socket.\n"); exit(1); } // Prepare UDP to bind port bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(port); // **************************************** // Receive questions // **************************************** // Bind application to UDP port int res = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if(res < 0) { printf("Error binding to port %d.\n", servaddr.sin_port); if(servaddr.sin_port <= 1024) { printf("To use ports below 1024 you may need additional permitions. Try to use a port higher than 1024.\n"); } else { printf("Please make sure this UDP port is not being used.\n"); } exit(1); } #ifdef DEBUG printf("Criacao named pipe para as estatisticas\n."); #endif char* n_pipe = ptr_config->Named_pipe; if(verifica_ficheiros(n_pipe) == 1) { printf("Named pipe ja existente! A eliminar...\n"); unlink(n_pipe); } if(((np = mkfifo(n_pipe, O_CREAT|O_EXCL|0600)<0)) && (errno != EEXIST)) { perror("mkfifo"); exit(1); } if (np != 0) { fprintf(stderr, "Impossivel criar fifo %s\n", n_pipe); return 1; } if((np = open(n_pipe, O_RDWR)) < 0) { perror("Opening Named Pipe"); exit(1); } } #ifdef DEBUG printf("A sair = %d\n", getpid()); #endif #ifdef DEBUG printf("Criacao Processo de estatisticas\n"); #endif if(cfg_process != 0) { stats_process = fork(); if(stats_process == 0) { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("Signal ignore error"); exit(1); } #ifdef DEBUG printf("RELEASE STATS.\n"); #endif } else { usleep(200000); if(signal(SIGALRM, SIG_IGN) == SIG_ERR) { perror("SIGALRM Ignore error"); exit(1); } } } #ifdef DEBUG printf("Quem chega primeiro = %d\n", getpid()); #endif if(cfg_process != 0 && stats_process != 0) { #ifdef DEBUG printf("A preencher struct para argumento da funcao do thread.\n"); #endif struct thread_data t_data; t_data.normal = fila_normal; t_data.prioridade = fila_prioridade; t_data.domains = l_domains; int N_THREADS = ptr_config->N_threads; p_threads = malloc(sizeof(*p_threads) * N_THREADS); #ifdef DEBUG printf("A criar a pool de threads.\n"); #endif for(i=0;i < N_THREADS;i++) { pthread_create(p_threads+i, NULL, requester, (void*)&t_data); } usleep(50000); printf("\n\n-- Waiting for DNS message --\n\n"); } while(1) { if((cfg_process == 0) && (ptr_config->saida == 1)) { // MODO MANUNTENCAO file2memory("config.txt"); ptr_config->saida = 0; usleep(100000); printf("\n-- Waiting for DNS message --\n"); } if(cfg_process != 0 && stats_process != 0) { // GESTOR PEDIDOS usleep(200000); len = sizeof(dest); // Thread blocking! if(recvfrom (sockfd, (unsigned char*)buf, 65536 , 0 , (struct sockaddr*)&dest , &len) < 0) { perror("Error in recvfrom"); exit(1); } printf("DNS message received\n"); // Process received message dns = (struct DNS_HEADER*) buf; qname = (unsigned char)buf[sizeof(struct DNS_HEADER)]; reader = &buf[sizeof(struct DNS_HEADER)]; // We only need to process the questions // We only process DNS messages with one question // Get the query fields according to the RFC specification struct QUERY query; if(ntohs(dns->q_count) == 1) { // Get NAME query.name = convertRFC2Name(reader,buf,&stop); reader = reader + stop; // Get QUESTION structure query.ques = (struct QUESTION*)(reader); reader = reader + sizeof(struct QUESTION); // Check question type. We only need to process A records. if(ntohs(query.ques->qtype) == 1) { printf("A record request.\n\n"); } else { printf("NOT A record request!! Ignoring DNS message!\n"); continue; } } else { printf("\n\nDNS message must contain one question!! Ignoring DNS message!\n\n"); continue; } #ifdef DEBUG printf("ID PEDIDO = %d\n", dns->id); #endif /***** VALIDAR PEDIDO *****/ valido = 0; // 1. Verificar se e' localDomain (Se for, vai para a lista prioritaria) // TRABALHO DOS THREADS... if(strstr(query.name, ptr_config->localDomain) != NULL) { valido = 1; stat.pedidos_local += 1; insere_pedido(fila_prioridade, receber_info(query.name, &dest, dns->id, sockfd)); } else if(ptr_config->flag % 2 == 0) { // 2. Verificar se é um dos dominios autorizados (ptr_config->domains[]) for(i=0; i < ptr_config->n_domains; i++) { if(strstr(query.name, ptr_config->domains[i]) != NULL) { valido = 1; stat.pedidos_externos += 1; insere_pedido(fila_normal, receber_info(query.name, &dest, dns->id, sockfd)); break; } } } #ifdef DEBUG imprimir_fila(fila_normal); imprimir_fila(fila_prioridade); #endif if(valido == 1) { #ifdef DEBUG printf("A ENVIAR SINAL PARA A THREAD...\n"); #endif pthread_cond_signal(&cond); } else { if(ptr_config->flag % 2 != 0) { printf("Durante o modo de manuntencao apenas pedidos locais sao aceites!\n"); printf("A enviar 0.0.0.0...\n"); } else { printf("Pedido negado!\nDe momento os dominios aceites sao:\n"); for(i=0;i<ptr_config->n_domains;i++) { printf("-> Dominio %d = %s\n",i,ptr_config->domains[i]); } } sendReply(dns->id, query.name, inet_addr("0.0.0.0"), sockfd, dest); printf("\n\n-- Waiting for DNS message --\n\n"); } if(valido == 0) { stat.pedidos_negados += 1; } stat.total_pedidos += 1; // Enviar dados das ESTATISTICAS para o named pipe aqui #ifdef DEBUG printf("A escrever estatisticas para o named pipe\n."); #endif write(np, &stat, sizeof(struct stats)); } if (stats_process == 0 && cfg_process != 0) { // STATS Process signal(SIGALRM, handler_alarm); Config* ptr; if ((ptr = shmat(shmID, NULL, 0)) == (Config *) -1) { perror("error in shmat"); exit(1); } struct stats st; char* n_pipe = ptr_config->Named_pipe; if((r = open(n_pipe, O_RDONLY)) < 0) { perror("Child open Named pipe"); exit(1); } read(r, &st, sizeof(struct stats)); linha(st.data_hora_arranque); time_t clk2 = time(NULL); strcpy(st.data_info, ctime(&clk2)); linha(st.data_info); t_p = st.total_pedidos; p_n = st.pedidos_negados; p_l = st.pedidos_local; p_e = st.pedidos_externos; strcpy(d_a, st.data_hora_arranque); strcpy(u_i, st.data_info); alarm(FREQ); } } return 0; }