language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "CacheSimulator.h" #define MAX 10 struct memtrace_type { unsigned long addr; unsigned char flag; }; struct memtrace_buf_type { int pos; struct memtrace_type memtrace[MAX]; }; pthread_key_t keyp; pthread_once_t init_done = PTHREAD_ONCE_INIT; int memtrace_save(struct memtrace_buf_type* memtrace_buf) { FILE* fp; char path[50]; int wstat; pthread_t tid = pthread_self(); sprintf(path, "/home2/pocean/memtrace/memtrace/%u", (unsigned int)tid); fp = fopen(path, "a+"); if (NULL == fp) { printf("file open error!\n"); return 0; } wstat = fwrite(memtrace_buf->memtrace, sizeof(struct memtrace_type), memtrace_buf->pos + 1, fp); if (wstat != memtrace_buf->pos+1) { printf("error in write file!\n"); } fclose(fp); return 0; } void memtrace_finish(void* memtrace_buf) { printf("zhixingle xi gou!\n"); memtrace_save((struct memtrace_buf_type*)memtrace_buf); if (NULL != memtrace_buf) { free(memtrace_buf); } } void memtrace_init(void) { pthread_key_create(&keyp, memtrace_finish); init_instr_count(); init_memory_statistics(); init_mem_buf(); } int showtrace(unsigned long addr, int flag) { struct memtrace_buf_type* memtrace_buf = NULL; pthread_once(&init_done, memtrace_init); memtrace_buf = pthread_getspecific(keyp); if (NULL == memtrace_buf) { memtrace_buf = (struct memtrace_buf_type*)malloc(sizeof(struct memtrace_buf_type)); memtrace_buf->pos = 0; pthread_setspecific(keyp, (void*)memtrace_buf); } if (memtrace_buf->pos == MAX) { memtrace_save(memtrace_buf); memtrace_buf->pos = 0; } (memtrace_buf->memtrace)[memtrace_buf->pos].addr = addr; (memtrace_buf->memtrace)[memtrace_buf->pos].flag = (unsigned char)flag; memtrace_buf->pos += 1; return 0; }
C
#include <mpi.h> #include <math.h> #include "func.h" const double EPS = 1e-10; int SolveSystem(int n, int* mass, double* a, double* b, double* x, double* y, double* answer, int my_rank, int p){ int i, j, k, l, rank, first, last, flag[1]; int first_row, last_row, max_rows; double tmp, maxi, norm = 0.0, maxnorm = 0.0; flag[0] = 0; MPI_Status status; first_row = (n * my_rank) / p; last_row = (n * (my_rank + 1)) / p - 1; max_rows = last_row - first_row + 1; for (i = 0; i < n; ++i) // сначала вычисляем норму матрицы: считаем норму первой строки maxnorm += fabs(a[i]); for (i = 1; i < max_rows; ++i){ // сравниваем с нормами остальных строк, получаем норму подматрицы norm = 0; for (j = 0; j < n; ++j) norm += fabs(a[i * n + j]); if (norm > maxnorm) maxnorm = norm; } MPI_Allreduce (&maxnorm, &tmp, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); // считаем максимальную норму по подматрицам if (tmp < EPS){ // делим матрицу на нее, если необходимо for (i = 0; i < max_rows; ++i){ for (j = 0; j < n; ++j) a[i * n + j] /= tmp; b[i] /= tmp; } } for (i = 0; i < n; ++i){ if (i >= first_row && i <= last_row){ // сюда может войти только определенный узел rank = my_rank; // поэтому проверка на my_rank не требуется maxi = fabs(a[(i - first_row) * n + i]); l = i; for (j = i + 1; j < n; ++j) // поиск максимального элемента строки i if (fabs(a[(i - first_row) * n + j]) > maxi){ l = j; maxi = fabs(a[(i - first_row) * n + j]); } for (k = 0; k < p; ++k){ // отсылаем всем узлам номер данного узла if (k != my_rank) MPI_Send(&my_rank, 1, MPI_INT, k, 0, MPI_COMM_WORLD); } if (fabs(maxi) < EPS){ // если встретилась нулевая строка, то завершаем данный узел -1 flag[0] = -1; // всем остальным узлам передаем в переменной flag[0] -1 MPI_Bcast(&flag[0], 1, MPI_INT, rank, MPI_COMM_WORLD); return -1; } MPI_Bcast(&flag[0], 1, MPI_INT, rank, MPI_COMM_WORLD); for (k = 0; k < p; ++k) if (k != my_rank) MPI_Send(&l, 1, MPI_INT, k, 0, MPI_COMM_WORLD); // посылаем всем остальным узлам номер столбца с макс элементом if (l != i){ // если столбцы не совпадают, меняем столбец l на столбец i for (j = 0; j < max_rows; ++j){ tmp = a[j * n + i]; a[j * n + i] = a[j * n + l]; a[j * n + l] = tmp; } k = mass[i]; // не забываем про массив индексов mass[i] = mass[l]; mass[l] = k; } maxi = a[(i - first_row) * n + i]; for (j = i, k = 0; j < n; ++j, ++k){ // делим всю i-ю строчку на [i,i] элемент a[(i - first_row) * n + j] /= maxi; x[k] = a[(i - first_row) * n + j]; // записываем все в буфер } b[i - first_row] /= maxi; // не забываем про вектор x[k] = b[i - first_row]; // координату вектора записываем в последний элемент буффера for (k = 0; k < p; ++k) MPI_Send(&my_rank, 1, MPI_INT, k, 0, MPI_COMM_WORLD); // посылаем всем узлам номер текущего узла MPI_Bcast(x, n + 1, MPI_DOUBLE, rank, MPI_COMM_WORLD); // посылаем всем узлам вектор, состоящий из всех элементов // i строки, правее i-го элемента, последнее число - i элемент вектора } else{ MPI_Recv(&rank, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);// получаем номер искавшего макс элемент узла MPI_Bcast(&flag[0], 1, MPI_INT, rank, MPI_COMM_WORLD); // получаем значение флага, если оно -1, то завершаем узел -1 if (flag[0] == -1) return -1; MPI_Recv(&l, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); // получаем всеми узлами номер столбца с макс элементом if (l != i){ // если не совпадают, меняем for (j = 0; j < max_rows; ++j){ tmp = a[j * n + i]; a[j * n + i] = a[j * n + l]; a[j * n + l] = tmp; } k = mass[i]; // опять же индексы mass[i] = mass[l]; mass[l] = k; } } MPI_Recv(&rank, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); // получаем номер узла, из которого высылали буффер if (rank != my_rank) // получаем всеми остальными узлами буффер MPI_Bcast(x, n + 1, MPI_DOUBLE, rank, MPI_COMM_WORLD); for (j = first_row; j <= last_row; ++j){ // производим вычисления if (j != i){ // x[n - i] - координата вектора, (последний элемент буффера) b[j - first_row] -= x[n - i] * a[(j - first_row) * n + i]; // опять же, j строка большой матрицы - j - first_row строка for (k = n - 1; k >= i; --k) // матрицы узла a[(j - first_row) * n + k] -= a[(j - first_row) * n + i] * x[k - i]; } } } if (my_rank == 0){ // чтобы переставить в ответе индексы в соответствии с массивом for (i = 0; i < max_rows; ++i) // нулевым узлом объединяем все части вектора в один большой y[i] = b[i]; // сначала записываем часть нулевого узла if (p > 1){ for (k = 1; k < p; ++k){ MPI_Recv(&first, 1, MPI_INT, k, 0, MPI_COMM_WORLD, &status); // потом получаем части от других узлов вместе с MPI_Recv(&last, 1, MPI_INT, k, 1, MPI_COMM_WORLD, &status); // first_row и last_row этих узлов MPI_Recv(x, n, MPI_DOUBLE, k, 2, MPI_COMM_WORLD, &status); for (i = first; i <= last; ++i) // записываем в вектор эти части y[i] = x[i - first]; } } } else{ MPI_Send(&first_row, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); // всеми узлами посылаем нулевому узлу части вектора MPI_Send(&last_row, 1, MPI_INT, 0, 1, MPI_COMM_WORLD); // и first_row last_row MPI_Send(b, n, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD); } if (my_rank == 0) // в итоге имеем в нулевом узле вектор у for (i = 0; i < n; ++i) // составленный из всех частей answer[mass[i]] = y[i]; // переставляем в соответствии с индексами // и получаем в 0 процессе вектор answer return 0; }
C
// // primitiveRoot.c // ElGamal // // Created by Rokia on 6/6/17. // Copyright © 2017 Rokia. All rights reserved. // #include "primitiveRoot.h" #include "RandomGenerator.h" #include <gmp.h> void primitiveRoot_g(mpz_t p,mpz_t g1,unsigned int bitLength) { mpz_t p2,G,val; mpz_inits(p2,G,val,NULL); //using Sophie Germain prime numbers //generate(p2, p, bitLength, 2); //alternative to costly Sophie Germain prime numbers generation mpz_sub_ui(p2,p,1); mpz_div_ui(p2,p2,2); gmp_printf("p2 :%Zu \n",p2); generate(g1,p,0, 3); mpz_powm(G,g1,p2,p); if(mpz_cmp_ui(G,1)== 0) { //-g1 is a generator mpz_sub(g1,p,g1); } //verify that g1 is generator mpz_sub_ui(val,p,1); mpz_powm(G,g1,val,p); if(mpz_cmp_ui(G,1)!= 0) { printf("error primitive root\n"); return; } gmp_printf("g1 :%Zu \n",g1); mpz_clears(p2,G,val,NULL); }
C
#include <stdio.h> #include <stdlib.h> #ifndef STACK_H_INCLUDED #include "stack.h" #endif // STACK_H_INCLUDED //#ifndef MERGE_H_INCLUDED //#include "merge.h" //#endif // MERGE_H_INCLUDED #define exch(A,B) {int t = A; A = B; B=t;} void swap(int* x,int* y) { int tmp = *x; *x = *y; *y = tmp; return; } int partition(int a[],int l,int r) { int i = l-1,j=r; int v = a[r]; while(1) { while(a[++i] < v); while(a[--j] > v) if(j==l) break; if(i>=j) break; swap(&a[i],&a[j]); } swap(&a[r],&a[i]); return i; } /* void quickSort(int a[],int l,int r) { if(l>=r) return; int i = partition(a,l,r); quickSort(a,l,i-1); quickSort(a,i+1,r); return; }*/ /* void quickSort(int a[],int l,int r) { int sz = r - l + 1; stackInit(sz); stackPush(l); stackPush(r); while(!isStackEmpty()) {//printf("Hello world!\n"); int right = stackPop(); int left = stackPop(); //printf("\n (%d,%d) \n",left,right); if(left>=right) continue; int i = partition(a,left,right); if(i-left > right-i) { stackPush(left);stackPush(i-1); stackPush(i+1); stackPush(right); } else { stackPush(i+1); stackPush(right); stackPush(left);stackPush(i-1); } } return; } */ void merge(int a[],int aux[],int l,int m,int r) { int i,j; int num = r-l+1; //int* aux = malloc(sizeof(int)*num); //printf("%d,\n",num); for(i=l;i<=m;i++) aux[i] = a[i]; for(j=r;j>m; j--) aux[r-j+m+1] = a[j]; i =l;j=r; for(int k=l;k<=r;k++) { if(aux[i]>aux[j]) a[k] = aux[j--]; else a[k] = aux[i++]; } //free(aux); return; } void mergeSort(int a[],int aux[],int l,int r) { int mid; if(l>=r) return; mid = l + (r-l)/2; mergeSort(a,aux,l,mid); mergeSort(a,aux,mid+1,r); merge(a,aux,l,mid,r); } #define N 19 int main() { int a[N],aux[N]; for(int i=0;i<N;i++) { a[i] = rand()%100; printf("%d, ",a[i]); } printf("Hello world!\n"); //mergeInit(N); mergeSort(a,aux,0,N-1); // quickSort(a,0,N-1); for(int i=0;i<N;i++) { printf("%d, ",a[i]); } return 0; }
C
#include "server.h" #include <stdio.h> void test_server_1(void) { printf("TEST_SERVER_1\n"); Server server = server_create(30, 10, 3); printf("Created\n"); server_destroy(server); printf("Destroyed\n"); } void test_server_2(void) { printf("TEST_SERVER_2\n"); Server server = server_create(30, 10, 3); printf("Created\n"); server_run(server); server_destroy(server); printf("Destroyed\n"); } int main(void) { test_server_1(); test_server_2(); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef int TD; typedef struct list { TD node; struct list * next; }List; List *ph; List *create(TD val) { List *pnew; pnew= (List*)malloc(sizeof(List)); pnew->node = val; pnew->next = ph->next; return pnew; } List * push(TD val) { List *pc; pc = create(val); ph->next = pc; return pc; } int pop() { List *pt; pt = (List*)malloc(sizeof(List)); pt = ph->next; TD val = pt->node; ph->next = pt->next; free(pt); return val; } void print() { List *pd; pd = (List*)malloc(sizeof(List)); pd = ph; while(pd->next != ph) { pd=pd->next; printf("%d\n",pd->node); } } void main() { ph = (List *)malloc(sizeof(List)); ph ->next = ph; push(23); push(43); print(); printf("%d\n",pop()); }
C
/*************************************************************** main.c Handles the boot process of the ROM. ***************************************************************/ #include <libdragon.h> #include "debug.h" /********************************* Definitions *********************************/ // Use printf instead of usb_write #define USE_PRITNF 1 /*============================== main Initializes the ROM ==============================*/ int main(void) { // Initialize the debug library and say hello to the command prompt! #if USE_PRITNF debug_initialize(); debug_printf("Hello World!\n"); #else usb_initialize(); usb_write(DATATYPE_TEXT, "Hello World!\n", 13+1); #endif // Spin forever while(1) ; }
C
/* ** EPITECH PROJECT, 2017 ** my_cook ** File description: ** main.c */ #include "all.h" static void my_cook(int *error) { game_t *game = init_game(error); if (!game || *error != 0) return; start_animation(game); main_menu(game); free_game(game); } static void usage(void) { my_putstr_fd("My cook is a game created by Simon Meyer & Arnaud Sc", 1); my_putstr_fd("heid with de CSFML library.\n\nUSAGE:\n\t./my_cook\n", 1); my_putstr_fd("\nHOW TO PLAY:\n\tLook at the \"How to play menu\"\n", 1); my_putstr_fd("\tMove the mouse on the main menu to see some easter", 1); my_putstr_fd(" eggs.\n\nINTERACTION:\n\tCLICK\tSelect a button.\n", 1); my_putstr_fd("\tESCAPE\tPause the game or go on the last menu.\n\t", 1); my_putstr_fd("OTHER KEY\tCompose the recipe for the game.\n", 1); } int main(int ac, char **av) { int error = 0; if (ac == 1) my_cook(&error); else if (ac == 2 && my_strcmp(av[1], "-h") == 0) usage(); else { my_putstr_fd("Invalid argument.\n", 2); return (EXIT_ERROR); } if (error != 0) my_putstr_fd("\nAn error occured during the execution.\n\n", 2); return ((error == 0) ? (EXIT_SUCCESS) : (EXIT_ERROR)); }
C
# ident "a simple prog to emulate the functionality of ll | wc -l" # include <stdio.h> # include <stdlib.h> # include <unistd.h> # include <errno.h> # include <signal.h> int main () { pid_t pin; int pipe_fd[2]; if (pipe(pipe_fd) == -1) { perror("pipe"); exit (1); } if ((pin = fork()) == -1) { perror("fork"); exit (1); } if (pin > 0) /* this is parent(sender to pipe) */ { //close(stdout); /* close standard out */ close(1); /* close standard out */ close(pipe_fd[0]); /* close write end of the pipe */ //dup2(stdout, pipe_fd[1]); /* duplicate pipe's write end as stdout */ dup(pipe_fd[1]); execlp("ls", "ls", "-al", NULL); open(1); puts("parent:waiting for the child.\n"); wait(&pin); puts("parent:waiting over..\n"); exit (0); //return 0; } else /* This is child (reader from pipe)*/ { //close(stdin); close(0); close(pipe_fd[1]); //dup2(stdin, pipe_fd[0]); dup(pipe_fd[0]); execlp("wc", "wc", "-l", NULL); //exit (0); open(0); puts("child: returning..\n"); return 0; } }
C
#include <stdio.h> #include <stdlib.h> #include <wiringPi.h> int main() { int wTrig = 15; int wEcho = 16; wiringPiSetup(); pinMode(wTrig, OUTPUT); // 트리거는 내보내는 방향이므로 OUTPUT : 측정신호발사 pinMode(wEcho, INPUT); // 반사 신호 검출 while(1) { digitalWrite(wTrig, LOW); delayMicroseconds(100); // 트리거 신호를 위한 초기화 digitalWrite(wTrig, HIGH); delayMicroseconds(10); // 기본 밀리초 단위를 마이크로초로 변환해줌 : 10 us 의 트리거 신호 digitalWrite(wTrig, LOW); delayMicroseconds(200); // 실제로 발사까지 200us의 지연시간이 필요 while(digitalRead(wEcho) == LOW); // until HIGH : 처음에 LOW 상태이므로 수행 long start = micros(); // 현재 시간의 마이크로초 단위 count while(digitalRead(wEcho) == HIGH); // until HIGH long end = micros(); double dist = (end - start) * 0.17; printf("현재 시간의 마이크로 초 단위 : %ld\n", start); printf("현재 시간의 마이크로 초 단위 : %ld\n", end); printf("Distance : %.3fmm\n", dist); delay(1000); } }
C
#include <stdio.h> int solve1(long long a, long long b) { int score = 0; for (int i = 0; i < 40000000; i++) { a = (a * 16807) % 0x7fffffff; b = (b * 48271) % 0x7fffffff; if ((a & 0xffff) == (b & 0xffff)) { score++; } } return score; } int solve2(long long a, long long b) { int score = 0; for (int i = 0; i < 5000000; i++) { do { a = (a * 16807) % 0x7fffffff; } while (a & 0x3); do { b = (b * 48271) % 0x7fffffff; } while (b & 0x7); if ((a & 0xffff) == (b & 0xffff)) { score++; } } return score; } int main(void) { long long a = 703; long long b = 516; printf("Part 1: %d\n", solve1(a, b)); printf("Part 2: %d\n", solve2(a, b)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct corredor{ int id; char name[256]; char instituicao[256]; } corredor; void bubblesort_ID(struct corredor *vector, int tam){ int aux_int, i, j; char aux_string[256]; for(i=tam-1; i >= 1; i--){ for(j=0; j < i ; j++){ if(vector[j].id>vector[j+1].id) { //troca os ids aux_int = vector[j].id; vector[j].id = vector[j+1].id; vector[j+1].id = aux_int; //troca os nomes; strcpy(aux_string, vector[j].name); strcpy(vector[j].name, vector[j+1].name); strcpy(vector[j+1].name, aux_string); //troca instituicao strcpy(aux_string, vector[j].instituicao); strcpy(vector[j].instituicao, vector[j+1].instituicao); strcpy(vector[j+1].instituicao, aux_string); } } } } void bubblesort_NAME(struct corredor *vector, int tam){ int aux_int, i, j; char aux_string[256]; for(i=tam-1; i >= 1; i--){ for(j=0; j < i ; j++){ if(strcmp(vector[j].name, vector[j+1].name) >= 0){ //troca os ids aux_int = vector[j].id; vector[j].id = vector[j+1].id; vector[j+1].id = aux_int; //troca os nomes; strcpy(aux_string, vector[j].name); strcpy(vector[j].name, vector[j+1].name); strcpy(vector[j+1].name, aux_string); //troca instituicao strcpy(aux_string, vector[j].instituicao); strcpy(vector[j].instituicao, vector[j+1].instituicao); strcpy(vector[j+1].instituicao, aux_string); } } } } int main(){ struct corredor *corredores; int i, j, tam; char letra; char scan[256]; corredores = (struct corredor*) calloc(1, sizeof(struct corredor)); scanf("%s", scan); //printf("%s\n", scan); scanf("%s", scan); for(i = 0; strcmp(scan, "CAASO") != 0; i++){ corredores = (struct corredor*) realloc (corredores, (i+1)*sizeof(struct corredor)); strcpy(corredores[i].instituicao, "FEDERAL"); corredores[i].id = atoi(scan); scanf("%c", &letra); scanf("%c", &letra); for(j = 0; letra != '\n' ; j++){ corredores[i].name[j] = letra; scanf("%c", &letra); } corredores[i].name[j] = '\0'; scanf("%s", scan); } scanf("%s", scan); for(; strcmp(scan, "ID") != 0 && strcmp(scan, "NAME") != 0; i++){ corredores = (struct corredor*) realloc (corredores, (i+1)*sizeof(struct corredor)); strcpy(corredores[i].instituicao, "CAASO"); corredores[i].id = atoi(scan); scanf("%c", &letra); scanf("%c", &letra); for(j = 0; letra != '\n' ; j++){ corredores[i].name[j] = letra; scanf("%c", &letra); } corredores[i].name[j] = '\0'; scanf("%s", scan); if(i == 20) break; } tam = i; if(strcmp(scan, "ID") == 0){ bubblesort_ID(corredores, tam); } else { bubblesort_NAME(corredores, tam); } //print vector for(i = 0; i < tam; i++) { printf("%s %d %s\n",corredores[i].instituicao, corredores[i].id, corredores[i].name); } free(corredores); return 0; }
C
#ifndef AWS_COMMON_XML_PARSER_H #define AWS_COMMON_XML_PARSER_H /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/common/array_list.h> #include <aws/common/byte_buf.h> #include <aws/common/exports.h> struct aws_xml_parser; struct aws_xml_node; struct aws_xml_attribute { struct aws_byte_cursor name; struct aws_byte_cursor value; }; /** * Callback for when an xml node is encountered in the document. As a user you have a few options: * * 1. reject the document parsing at this point by returning false. This will immediately stop doc parsing. * 2. call aws_xml_node_traverse() on the node to descend into the node with a new callback and user_data. * 3. call aws_xml_node_as_body() to retrieve the contents of the node as text. * * return true to continue the parsing operation. */ typedef bool( aws_xml_parser_on_node_encountered_fn)(struct aws_xml_parser *parser, struct aws_xml_node *node, void *user_data); struct aws_xml_parser_options { /* xml document to parse. */ struct aws_byte_cursor doc; /* Max node depth used for parsing document. */ size_t max_depth; }; AWS_EXTERN_C_BEGIN /** * Allocates an xml parser. */ AWS_COMMON_API struct aws_xml_parser *aws_xml_parser_new( struct aws_allocator *allocator, const struct aws_xml_parser_options *options); /* * De-allocates an xml parser. */ AWS_COMMON_API void aws_xml_parser_destroy(struct aws_xml_parser *parser); /** * Parse the doc until the end or until a callback rejects the document. * on_node_encountered will be invoked when the root node is encountered. */ AWS_COMMON_API int aws_xml_parser_parse( struct aws_xml_parser *parser, aws_xml_parser_on_node_encountered_fn *on_node_encountered, void *user_data); /** * Writes the contents of the body of node into out_body. out_body is an output parameter in this case. Upon success, * out_body will contain the body of the node. */ AWS_COMMON_API int aws_xml_node_as_body(struct aws_xml_parser *parser, struct aws_xml_node *node, struct aws_byte_cursor *out_body); /** * Traverse node and invoke on_node_encountered when a nested node is encountered. */ AWS_COMMON_API int aws_xml_node_traverse( struct aws_xml_parser *parser, struct aws_xml_node *node, aws_xml_parser_on_node_encountered_fn *on_node_encountered, void *user_data); /* * Get the name of an xml node. */ AWS_COMMON_API int aws_xml_node_get_name(const struct aws_xml_node *node, struct aws_byte_cursor *out_name); /* * Get the number of attributes for an xml node. */ AWS_COMMON_API size_t aws_xml_node_get_num_attributes(const struct aws_xml_node *node); /* * Get an attribute for an xml node by its index. */ AWS_COMMON_API int aws_xml_node_get_attribute( const struct aws_xml_node *node, size_t attribute_index, struct aws_xml_attribute *out_attribute); AWS_EXTERN_C_END #endif /* AWS_COMMON_XML_PARSER_H */
C
#include<unistd.h> #include<stdlib.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<sys/shm.h> #include<errno.h> #include<sys/msg.h> #define NOT_READY -1 #define FILLED 0 #define TAKEN 1 #define GO 2 #define STOP 3 struct ints{ int num1, num2; }; struct Memory{ int status; int gostop; struct ints data; }; typedef struct MSGBUF{ long type; int one, two; }MsgBuf; int main(int argc, char** argv){ key_t key; if((key = ftok(".", 'B')) == -1){ perror("ftok() error"); exit(1); } int Qid; if((Qid = msgget(key, 0666 | IPC_CREAT)) == -1){ perror("msgget() error"); exit(2); } key_t key2; if((key2 = ftok(".",'B')) == -1){ perror("ftok error"); exit(3); } int shmid; if((shmid = shmget(key2, sizeof(struct Memory), IPC_CREAT | 0666)) == -1){ perror("shmget error"); exit(4); } MsgBuf buf; struct Memory *shm = (struct Memory*)shmat(shmid, NULL, 0); shm->status = NOT_READY; shm->gostop = GO; while(1){ if(msgrcv(Qid, (MsgBuf*) &buf, sizeof(buf), 0, 0) == -1){ break; } shm->data.num1 = buf.one; shm->data.num2 = buf.two; shm->status = FILLED; while(shm->status != TAKEN) ; printf("one:%d | two:%d\n", shm->data.num1, shm->data.num2); } shm->gostop = STOP; shmdt((void*)shm); exit(0); }
C
#include <stdlib.h> #include <string.h> #include <pthread.h> #include "boots.h" #include "bts_htab.h" #include "bts_bucket.h" void htab_free(htab_t *htab) { int i = 0; if (NULL == htab) { return; } if (htab->buckets) { for (i = 0; i < htab->size; i++) { bucket_clean(&htab->buckets[i]); } free(htab->buckets); } free(htab); } htab_t* htab_new(uint32_t size, uint32_t (*hash)(void *), int (*cmp)(void *, void *), void (*del)(void *)) { int i = 0; berr rv = E_FAIL; htab_t *htab = NULL; if (NULL == hash) { return NULL; } htab = malloc(sizeof(htab_t)); if (NULL == htab) { return NULL; } memset(htab, 0, sizeof(htab_t)); htab->buckets = malloc(sizeof(bucket_t) * size); if (NULL == htab->buckets) { htab_free(htab); return NULL; } memset(htab->buckets, 0, sizeof(bucket_t) * size); htab->size = 0; for (i = 0; i < size; i++) { rv = bucket_init(&htab->buckets[htab->size], cmp, del); if (E_SUCCESS != rv) { htab_free(htab); return NULL; } if (NULL != cmp) { htab->cmp = cmp; } htab->size++; } htab->hash = hash; return htab; } uint32_t htab_hash(htab_t* htab, void *key) { uint32_t hval = ERROR_HVAL; if ((NULL == htab) || (NULL == key)) { return ERROR_HVAL; } if (NULL == htab->hash) { return ERROR_HVAL; } if (0 == htab->size) { return ERROR_HVAL; } hval = htab->hash(key); if (ERROR_HVAL == hval) { return ERROR_HVAL; } hval = hval % htab->size; return hval; } bucket_t* htab_bucket_get(htab_t* htab, void *key) { uint32_t hval = 0; bucket_t *bucket = NULL; if ((NULL == htab) || (NULL == key)) { return NULL; } hval = htab_hash(htab, key); if (ERROR_HVAL == hval) { return NULL; } bucket = &htab->buckets[hval]; return bucket; } void* htab_cell_get(htab_t* htab, void *key) { bucket_t *bucket = NULL; bucket = htab_bucket_get(htab, key); if (NULL == bucket) { return NULL; } return bucket_cell_get(bucket, key); } berr htab_cell_add(htab_t *htab, void *obj, void *key) { bucket_t *bucket = NULL; bucket = htab_bucket_get(htab, key); if (NULL == bucket) { return E_FAIL; } return bucket_cell_add(bucket, obj); } void htab_cell_del(htab_t *htab, void *key) { bucket_t *bucket = NULL; bucket = htab_bucket_get(htab, key); if (NULL == bucket) { return; } bucket_cell_del(bucket, key); } /* End of file */
C
#include<stdio.h> void getLPS(char *,int); //function to get LPS array ie. values correspoinding to largest length of same prefix or suffix pattern .. void findMatch(char *,char * , int , int); // to find if pattern matches or not .. int lps[10]; main() { char pat[10]; char text[10]; int m =0 , n=0 , i=0; gets(pat); gets(text); while(pat[i]!='\0') { m++; i++; } i=0; while(text[i]!='\0') { n++; i++; } //printf("%d %d",m,n); getLPS(pat,m); /* for(i=0;i<m;i++) { printf("%d\n",lps[i]); }*/ findMatch(text,pat,n,m); } void getLPS(char *pat,int m) { int len=0; int i=1; lps[0]=0; while(i<m) { if(pat[i]==pat[len]) { len++; lps[i]=len; i++; } else { if(len!=0) { len=lps[len-1]; //backtrack .. } else { lps[i]=0; i++; } } } } void findMatch(char *text,char *pat,int n,int m) { int i =0 , len=0; while(i<n) { if(pat[len]==text[i]) { i++; len++; } if(len==m) { printf("Pattern found \n"); len=lps[len-1]; // i++; } else if(pat[len] !=text[i]) { if(len!=0) { len=lps[len-1]; } else { i++; } } } }
C
#include<stdio.h> void main() { int a,count=0; printf("enter the number"); scanf("%d",&a); while(a>0) { a=a/10; count++; } printf("%d",count); }
C
/* CH-230-A a4 p8.c Amartya Vats [email protected] */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> void print_matrix(int a[30][30], int n){ printf("The entered matrix is:\n"); for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ printf("%d ", a[i][j]); } printf("\n"); } } void secondary_diagonal(int a[30][30], int n){ printf("Under the secondary diagonal:\n"); for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ if ((i + j) > n -1){ printf("%d ", a[i][j]); } } } printf("\n"); } int main () { int arry[30][30]; int n; scanf("%d\n",&n); for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ scanf("%d", &arry[i][j]); } } print_matrix(arry, n); secondary_diagonal(arry,n); return 0; }
C
#include "encoder.h" int _is_in_array(char n, char* arr, int len) { if(arr == NULL || len == 0) return -1; int i; for(i=0; i<len; i++) { if(*(arr+i)==n) return 1; } return -1; } int _make_encode_array(char* arr, char* password) { if(password==NULL || arr==NULL) return -1; if(strlen(password) < 8) return -2; int i, idx=0; char h, l; for(i=0; i<16; i++) arr[i]=-1; for(i=0; i<8; i++) { h = *(password+i) >> 4; l = *(password+i) & 0x0f; while(_is_in_array(h, arr, 16)>0) h = (h+1)%16; *(arr+idx) = h; while(_is_in_array(l, arr, 16)>0) l = (l+1)%16; *(arr+idx+1) = l; idx+=2; } return 0; } int _make_decode_array(char* decode, char* password) { char encode[16]; int re = _make_encode_array(encode, password); if(re < 0) return re; int i; for(i=0; i<16; i++) { decode[encode[i]] = i; } return 0; } void _do_code(char* data, int len, char* code) { int i; for(i=0; i<len; i++) data[i] = (code[data[i] >> 4 & 0xf] << 4) + code[data[i] & 0xf]; } int encode(char* data, int len, char* password) { char code[16]; int re = _make_encode_array(code, password); if(re < 0) return re; _do_code(data, len, code); return 0; } int decode(char* data, int len, char* password) { char code[16]; int re = _make_decode_array(code, password); if(re < 0) return re; _do_code(data, len, code); return 0; } /* test */
C
/* File: list.c Abstract: Generic Linked-List ADT handling implementation */ #include "list.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /*structs*/ struct List_ { PNode Head; CLONE_ELEM cloneElem; DESTROY_ELEM destroyElem; COMPARE_ELEM compareElem; PRINT_ELEM printElem; PNode Iter; }; struct NODE_ { PElem pElem; PNode PNext; }; /*helper functions*/ PNode createNode(PElem, CLONE_ELEM); /*interface functions*/ /* Function: ListCreate Abstract: Creates a new generic linked list ADT that supports numerous functions Parameters: cloneElem - A user function that clones an elemnt from designated type destroyElem - A user function that free the memory allocated to an elemnt from designated type compareElem - A user function that compares between 2 elements from designated type according to the user wish printElem - A user function that prints an elemnt from designated type Returns: A pointer from type struct List to the list itself. If the list creation fails , return NULL. */ PList ListCreate(CLONE_ELEM cloneElem, DESTROY_ELEM destroyElem, COMPARE_ELEM compareElem, PRINT_ELEM printElem) { PList pL; if ((!cloneElem) || (!destroyElem) || (!compareElem) || (!printElem)) return NULL; pL = (PList)malloc(sizeof(struct List_)); if (!pL) return NULL; pL->Head = NULL; pL->cloneElem = cloneElem; pL->destroyElem = destroyElem; pL->compareElem = compareElem; pL->printElem = printElem; return pL; } /* Function: ListDestroy Abstract: Destroys a list ADT - Frees a list and all the allocated memory used in the list Parameters: pL - A pointer from type struct List to the list itself Returns: -- */ void ListDestroy(PList pL) { if (!pL) return; PNode pE; while (pL->Head) { pE = pL->Head; pL->Head=pL->Head->PNext; pL->destroyElem(pE->pElem); free(pE); } free(pL); } /* Function: ListAdd Abstract: Add's an element to the list. Creates a Node with the element as a KEY and links it to the list Parameters: pL - A pointer from type struct List to the list itself pE - A pointer to a generic element Returns: Result - FAIL if the add failed or SUCCESS if it succeded */ Result ListAdd(PList pL, PElem pE) {///need to add clone function if (!pL || !pE) return FAIL; PNode pN=pL->Head; PNode pnewN = createNode(pE, pL->cloneElem); if (!pnewN) return FAIL; /*adding first node - initialize Iterator to the first node*/ if (!pN) { pL->Head = pnewN; pL->Iter = pL->Head; return SUCCESS; } while (pN->PNext) pN = pN->PNext; pN->PNext = pnewN; return SUCCESS; } /* Function: ListRemove Abstract: Searches an element in the list and Removes the element from the list if found Parameters: pL - A pointer from type struct List to the list itself pE - A pointer to a generic element that user wants to remove Returns: Result - FAIL if the remove failed or SUCCESS if it succeded */ Result ListRemove(PList pL, PElem pE) { if (!pE || !pL) return FAIL; PNode pCur = pL->Head; /*the first node is the needed one*/ if (pL->compareElem(pCur->pElem, pE)) { pL->Head = pL->Head->PNext; pL->destroyElem(pCur->pElem); free(pCur); return SUCCESS; } /*advanced pCur until different or reaching last node*/ while (!(pL->compareElem(pCur->PNext->pElem, pE))) { pCur = pCur->PNext; if (!pCur->PNext) break; } if (!pCur->PNext) return FAIL; else { PNode tmp = pCur->PNext; pCur->PNext = pCur->PNext->PNext; pL->destroyElem(tmp->pElem); free(tmp); return SUCCESS; } } /* Function: ListGetFirst Abstract: Set the Iterator pointer, a generic Pointer in the Struct List type, to points on the first element in the list Parameters: pL - A pointer from type struct List to the list itself Returns: Result - : A pointer to a generic element - the element that the iterator points on - the first element in the list */ PElem ListGetFirst(PList pL) { if (!pL || !pL->Head) return NULL; pL->Iter = pL->Head; return pL->Iter->pElem; } /* Function: ListGetNext Abstract: Set the Iterator pointer, a generic Pointer in the Struct List type, to points on the next element in the list from the element he point now Parameters: pL - A pointer from type struct List to the list itself Returns: Result - : A pointer to a generic element - the element that the iterator points on */ PElem ListGetNext(PList pL) { if (!pL) return NULL; if (!pL->Iter) return NULL; pL->Iter = pL->Iter->PNext; if (!pL->Iter) return NULL; return pL->Iter->pElem; } /* Function: ListCompare Abstract: Compare between 2 lists Parameters: pL1 - A pointer from type struct List to the list itself pL2 - A pointer from type struct List to the list itself Returns: TRUE if the lists are equal or FALSE otherwise */ BOOL ListCompare(PList pL1, PList pL2) { PNode pCur1 = pL1->Head; PNode pCur2 = pL2->Head; /*both lists are empty*/ if (!pCur1 && !pCur2) return TRUE; /*one list is empty*/ if ((!pCur1 && pCur2)||(pCur1 && !pCur2)) return FALSE; /* iterate comparison on lists elemnts, stops when the elemnts are different or when the lists are finished*/ while (pL1->compareElem(pCur1->pElem, pCur2->pElem)) { pCur1 = pCur1->PNext; pCur2 = pCur2->PNext; if (!pCur1 || !pCur2) break; } if (!pCur1 && !pCur2) return TRUE; return FALSE; } /* Function: ListPrint Abstract: Prints the List according to a designated pattern Parameters: pL - A pointer from type struct List to the list itself Returns: -- */ void ListPrint(PList pL) { PNode pCur = pL->Head; printf("["); while (pCur){ pL->printElem(pCur->pElem); pCur = pCur->PNext; } printf("]\n"); } /*helper functions*/ /* Function: createNode Abstract: Creates a new "struct node" type , and clones the element entered by user to be the KEY of the node. later linkes the node to the list Parameters: pE - A generic element that will be cloned and set as the node KEY cloneElem - A user function that clones an elemnt from designated type Returns: A pointer to the Node created */ PNode createNode(PElem pE, CLONE_ELEM cloneElem) { PNode pN; pN = (PNode)malloc(sizeof(struct NODE_)); if (!pN) return NULL; // saving the external elem in the node. pN->pElem = cloneElem(pE); pN->PNext = NULL; return pN; }
C
/* ** por compatibilidad se omiten tildes ** ================================================================================ TRABAJO PRACTICO 3 - System Programming - ORGANIZACION DE COMPUTADOR II - FCEN ================================================================================ definicion de las rutinas de atencion de interrupciones */ #include "defines.h" #include "idt.h" #include "isr.h" #include "screen.h" #include "tss.h" idt_entry idt[255] = { }; idt_descriptor IDT_DESC = { sizeof(idt) - 1, (unsigned int) &idt }; /* La siguiente es una macro de EJEMPLO para ayudar a armar entradas de interrupciones. Para usar, descomentar y completar CORRECTAMENTE los atributos y el registro de segmento. Invocarla desde idt_inicializar() de la siguiene manera: void idt_inicializar() { IDT_ENTRY(0); ... IDT_ENTRY(19); ... } */ #define IDT_ENTRY(numero) \ idt[numero].offset_0_15 = (unsigned short) ((unsigned int)(&_isr ## numero) & (unsigned int) 0xFFFF); \ idt[numero].segsel = (unsigned short) 0x08; \ idt[numero].attr = (unsigned short) 0x8E00; \ idt[numero].offset_16_31 = (unsigned short) ((unsigned int)(&_isr ## numero) >> 16 & (unsigned int) 0xFFFF); void idt_inicializar() { // Excepciones IDT_ENTRY(0); IDT_ENTRY(1); IDT_ENTRY(2); IDT_ENTRY(3); IDT_ENTRY(4); IDT_ENTRY(5); IDT_ENTRY(6); IDT_ENTRY(7); IDT_ENTRY(8); IDT_ENTRY(9); IDT_ENTRY(10); IDT_ENTRY(11); IDT_ENTRY(12); IDT_ENTRY(13); IDT_ENTRY(14); IDT_ENTRY(15); IDT_ENTRY(16); IDT_ENTRY(17); IDT_ENTRY(18); IDT_ENTRY(19); IDT_ENTRY(20); IDT_ENTRY(32); idt[32].attr = (unsigned short) 0x8E00; IDT_ENTRY(33); idt[33].attr = (unsigned short) 0x8E00; IDT_ENTRY(102); idt[102].attr = (unsigned short) 0xEE00; } void manejo_teclado(char scanCode, char debug_en_screen){ char valor = 1; int player; direccion dir; if (debug_en_screen == 0 || scanCode == 0x15) { if(scanCode == 0x2a){ valor = '1'; game_lanzar(1); } else if(scanCode == 0x36){ valor = '2'; game_lanzar(2); } else if(scanCode == 0x1f){ valor = 's'; dir = ABA; player = 0; game_mover_cursor(player,dir); } else if(scanCode == 0x1e){ valor = 'a'; dir = IZQ; player = 0; game_mover_cursor(player,dir); } else if(scanCode == 0x20){ valor = 'd'; dir = DER; player = 0; game_mover_cursor(player,dir); } else if(scanCode == 0x11){ valor = 'w'; dir = ARB; player = 0; game_mover_cursor(player,dir); } else if(scanCode ==0x17 ){ valor = 'i'; dir = ARB; player = 1; game_mover_cursor(player,dir); } else if(scanCode == 0x24){ valor = 'j'; dir = IZQ; player = 1; game_mover_cursor(player,dir); } else if(scanCode == 0x25){ valor ='k' ; dir = ABA; player = 1; game_mover_cursor(player,dir); } else if(scanCode == 0x26 ){ valor = 'l'; dir = DER; player = 1; game_mover_cursor(player,dir); } else if(scanCode == 0x15){ //modo debug valor = 'y'; lanzar_modo_debug(); } } print_char(valor, 79, 0, (unsigned short)0x0E); }
C
#include <assert.h> #include <stdio.h> #include "minmax_list.h" #include "test_utils.h" void test_get_min_singleton() { printf(" verifying min of [1] is 1...\n"); minmax_list *p_list = singleton_list(); assert (get_min(p_list) == 1); printf(" min of [1] is 1: OK!\n"); } void test_get_min_simple_list() { printf(" verifying min of [-1, 2, 4] is -1...\n"); minmax_list *p_list = simple_list(); assert (get_min(p_list) == -1); printf(" min of [-1, 2, 4] is -1: OK!\n"); } int main(void) { printf("--- tests for get_min\n"); test_get_min_singleton(); test_get_min_simple_list(); printf("--- tests for get_min: OK!\n"); return 0; }
C
#include <stdio.h> #include "MK64F12.h" #include "GPIO.h" #include "RGB.h" #include "DataTypeDefinitions.h" int main(void) { GPIO_clockGating(GPIO_A); /*Habilitamos los clocks de los puertos A,B,C y E*/ GPIO_clockGating(GPIO_B); GPIO_clockGating(GPIO_C); GPIO_clockGating(GPIO_E); GPIO_pinControlRegisterType pinControlRegisterGPIO = GPIO_MUX1; /*establecemos que vamos a utilizarlos como GPIO*/ GPIO_pinControlRegister(GPIO_B,BIT21,&pinControlRegisterGPIO); GPIO_pinControlRegister(GPIO_B,BIT22,&pinControlRegisterGPIO); GPIO_pinControlRegister(GPIO_E,BIT26,&pinControlRegisterGPIO); GPIO_dataDirectionPIN(GPIO_B,GPIO_OUTPUT, BIT21);/*Declaramos que los pines referentes a los LEDS van a ser OUTPUTS*/ GPIO_dataDirectionPIN(GPIO_B,GPIO_OUTPUT,BIT22); GPIO_dataDirectionPIN(GPIO_E,GPIO_OUTPUT,BIT26); PORTC->PCR[6] = 0x00000103;/* GPIO + PE + PS para los switches*/ PORTA->PCR[4] = 0x00000103; uint8 color; uint8 color2; uint32 inputValueSW2; uint32 inputValueSW3; while(1){ inputValueSW2 = GPIOC->PDIR; inputValueSW2 = inputValueSW2 & 0x40; /*obtenemos direccion y monemos mascara para agarrar el pin del SW2 y SW3*/ inputValueSW3 = GPIOA->PDIR; inputValueSW3 = inputValueSW3 & 0x10; inputValueSW2 = inputValueSW2 >> 6; inputValueSW3 = inputValueSW3 >> 3; if(FALSE == inputValueSW2){ /*al presionar SW2 restamos 1 al contador */ if(color > 0){ color2 = color2 - 1; color = color2; } } if(FALSE == inputValueSW3){/*al presionar SW3 sumamos 1 al contador */ if(color < 4){ color2 = color2 + 1; color = color2; } } if(FALSE == inputValueSW3 && FALSE == inputValueSW2 ){ /*Al presionar ambos establecemos el valor del contador a 5 para que nos mande al blanco*/ color = 5 ; } switch (color){ /*Switch case para cada uno de los colores en el orden que deben verse*/ case 0: green(); delay(650000); break; case 1: blue(); delay(650000); break; case 2: purple(); delay(650000); break; case 3: red(); delay(650000); break; case 4: yellow(); delay(650000); break; case 5: white(); delay(650000); break; default: break; } } return 0; }
C
/* backup - backup a directory Author: Andy Tanenbaum */ /* This program recursively backs up a directory. It has two typical uses: * * 1. Backing up a directory to 1 or more diskettes * 2. Backing up RAM disk to a shadow directory on hard disk * * The backup directory or medium may be empty, in which case, the entire * source directory is copied, or it may contain an old backup, in which * case only those files that are new or out of date are copied. In this * respect, 'backup' resembles 'make', except that no 'makefile' is needed. * The backed up copy may optionally be compressed to save space. * * The following flags exist: * * -d At the top level, only back up directories (not loose files) * -j Don't copy junk: *.o, *.Z, *.bak, *.log, a.out, and core * -m If ENOSPC encountered, ask for another diskette * -n No directories, only loose files are backed up * -s Don't copy *.s files * -t set creation date of target-file equal to cdate of source-file * -v Verbose (announce what is being done) * -z Compress the backed up files * */ #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <fcntl.h> #include <utime.h> #define COPY_SIZE 4096 #define MAX_ENTRIES 512 #define DIR_ENT_SIZE 16 #define NAME_SIZE 14 #define MAX_PATH 256 #define NONFATAL 0 #define FATAL 1 #define NO_SAVINGS 512 /* compress can return code 2 */ #define OUT_OF_SPACE 2 typedef unsigned short unshort; struct dir_buf { /* list of the src directory */ unshort ino; char name[NAME_SIZE]; } dir_buf[MAX_ENTRIES]; struct sorted { int mode; /* file mode */ char *namep; /* pointer to name in dir_buf */ long acctime; /* time of last access */ long modtime; /* time of last modification */ } sorted[MAX_ENTRIES]; char copybuf[COPY_SIZE]; unshort dflag, jflag, mflag, nflag, rflag, sflag, tflag, vflag, zflag; extern int errno; extern char *environ; main(argc, argv) int argc; char *argv[]; { int i, ct, n, m, fd; char *dir1, *dir2, *cp, c; /* Get the flags. */ sync(); if (argc < 3 || argc > 4) usage(); if (argc == 4) { cp = argv[1]; if (*cp++ != '-') usage(); while ((c = *cp++) != '\0') { switch (c) { case 'd': dflag++; break; case 'j': jflag++; break; case 'm': mflag++; break; case 'n': nflag++; break; case 's': sflag++; break; case 'r': rflag++; break; case 't': tflag++; break; case 'v': vflag++; break; case 'z': zflag++; break; default: usage(); } } dir1 = argv[2]; dir2 = argv[3]; } else { dir1 = argv[1]; dir2 = argv[2]; } /* Read in the source directory */ fd = open(dir1, O_RDONLY); if (fd < 0) error(FATAL, "cannot open ", dir1, ""); ct = read(fd, &dir_buf[0], MAX_ENTRIES * DIR_ENT_SIZE); close(fd); if (ct == MAX_ENTRIES * DIR_ENT_SIZE) error(FATAL, "directory ", dir1, " is too large"); /* Create the target directory. */ maketarget(dir2); /* Stat all the entries. */ n = ct / DIR_ENT_SIZE; m = stat_all(dir1, n); /* Remove non-entries and sort what's left. */ sort_dir(m); /* Process each of the m entries one at a time. */ process(m, dir1, dir2); exit(0); } maketarget(dir2) char *dir2; { /* The target directory is created if it does not already exist. */ char *p, c, dbuf[MAX_PATH]; if (access(dir2, 6) == 0) return; /* if target exists, we're done */ if (make_dir(dir2) == 0) return; /* we just made it */ /* We have to try creating all the higher level directories. */ strcpy(dbuf, dir2); p = dbuf + 1; while (1) { while (*p != '/' && *p != '\0') p++; c = *p; /* either / or \0 */ *p = 0; make_dir(dbuf); if (c == '\0') return; *p = c; p++; } } int make_dir(dir) char *dir; { /* Create a directory. */ int pid, status; if ((pid = fork()) < 0) error(FATAL, "cannot fork off mkdir to create ", dir, ""); if (pid > 0) { /* Parent process waits for child (mkdir). */ wait(&status); return(status); } else { /* Child process executes mkdir */ close(2); /* don't want mkdir's error messages */ execle("/bin/mkdir", "mkdir", dir, (char *) 0, environ); execle("/usr/bin/mkdir", "mkdir", dir, (char *) 0, environ); error(FATAL, "cannot execute mkdir", "", ""); } } int stat_all(dir1, n) char *dir1; int n; { /* Stat all the directory entries. By doing this all at once, the disk * head can stay in the inode area. */ int i, j; char cbuf[MAX_PATH]; struct stat s; struct dir_buf *dp; struct sorted *sp; for (i = 0; i < n; i++) { /* Mark "." and ".." as null entries, as well as unstatable ones. */ if (strcmp(dir_buf[i].name, ".") == 0) dir_buf[i].ino = 0; if (strcmp(dir_buf[i].name, "..") == 0) dir_buf[i].ino = 0; if (dir_buf[i].ino == 0) continue; /* Stat the file. */ strcpy(cbuf, dir1); strncat(cbuf, "/", 1); strncat(cbuf, dir_buf[i].name, NAME_SIZE); if (stat(cbuf, &s) < 0) { error(NONFATAL, "cannot stat ", cbuf, ""); dir_buf[i].ino = 0; /* mark as unusable */ continue; } sorted[i].mode = s.st_mode; sorted[i].acctime = s.st_atime; sorted[i].modtime = s.st_mtime; sorted[i].namep = dir_buf[i].name; } /* Squeeze out all the entries who ino field is 0. */ j = 0; for (i = 0; i < n; i++) { if (dir_buf[i].ino != 0) { sorted[j] = sorted[i]; j++; } } return(j); } int sort_dir(m) int m; { /* Sort the directory using bubble sort. */ struct sorted *sp1, *sp2; for (sp1 = &sorted[0]; sp1 < &sorted[m - 1]; sp1++) { for (sp2 = sp1 + 1; sp2 < &sorted[m]; sp2++) { if (strncmp(sp1->namep, sp2->namep, NAME_SIZE) > 0) swap(sp1, sp2); } } } process(m, dir1, dir2) int m; char *dir1, *dir2; { /* Process each entry in sorted[]. If it is a regular file, stat the target * file. The the source is newer, copy it. If the entry is a directory, * recursively call the entire program to process the directory. */ int er, fmode, res, namlen; struct sorted *sp; struct stat s; char cbuf[MAX_PATH]; for (sp = &sorted[0]; sp < &sorted[m]; sp++) { fmode = sp->mode & S_IFMT; if (fmode == S_IFREG) { /* Regular file. Construct target name and stat it. */ strcpy(cbuf, dir2); strncat(cbuf, "/", 1); strncat(cbuf, sp->namep, NAME_SIZE); namlen = strlen(sp->namep); if (sp->namep[namlen - 2] != '.' || sp->namep[namlen - 1] != 'Z') if (zflag && (namlen <= (NAME_SIZE - 2))) strncat(cbuf, ".Z", 2); er = stat(cbuf, &s); if (er < 0 || sp->modtime > s.st_mtime) { res = copy(dir1, sp, cbuf); } else { res = NONFATAL; } /* Check status of the copy. */ if (res == OUT_OF_SPACE) { printf("Out of space while copying to %s\n", cbuf); /* We ran out of space copying a regular file. */ if (mflag == 0) error(FATAL,"Disk full. Backup aborted","",""); /* If -m, ask for new diskette and continue. */ newdisk(dir2); sp--; continue; } } else if (fmode == S_IFDIR) { /* Directory. Execute this program recursively. */ copydir(dir1, dir2, sp->namep); } else if (fmode == S_IFBLK || fmode == S_IFCHR) { /* Special file. */ strncpy(cbuf, sp->namep, NAME_SIZE); printf("%s is special file. Not backed up.\n", cbuf); } } } swap(sp1, sp2) struct sorted *sp1, *sp2; { /* Swap two directory entries. */ struct sorted d; d = *sp1; *sp1 = *sp2; *sp2 = d; } int copy(dir1, sp, cbuf2) struct sorted *sp; char *dir1, *cbuf2; { /* Copy a regular file. */ int fd1, fd2, nr, nw, res, n, namlen; char cbuf1[MAX_PATH], *p; /* If the -j or -s flags were given, suppress certain files. */ p = sp->namep; n = strlen(p); if (jflag) { if (strcmp(p, "a.out") == 0) return(0); if (strcmp(p, "core") == 0) return (0); if (strcmp(p + n - 2, ".o") == 0) return (0); if (strcmp(p + n - 2, ".Z") == 0) return (0); if (strcmp(p + n - 4, ".bak") == 0) return (0); if (strcmp(p + n - 4, ".log") == 0) return (0); } if (sflag) { if (strcmp(p + n - 2, ".s") == 0) return(0); } res = 0; if (dflag) return(0); /* backup -d means only directories */ strcpy(cbuf1, dir1); strncat(cbuf1, "/", 1); strncat(cbuf1, sp->namep, NAME_SIZE); /* cbuf1 = source file name */ /* At this point, cbuf1 contains the source file name, cbuf2 the target. */ fd1 = open(cbuf1, O_RDONLY); if (fd1 < 0) { error(NONFATAL, "cannot open ", cbuf1, ""); return(res); } fd2 = creat(cbuf2, (sp->mode | S_IWUSR) & 07777); if (fd2 < 0) { if (errno == ENFILE) { close(fd1); return(OUT_OF_SPACE); } error(NONFATAL, "cannot create ", cbuf2, ""); close(fd1); return(res); } /* Both files are now open. Do the copying. */ namlen = strlen(sp->namep); if (sp->namep[namlen - 2] != '.' || sp->namep[namlen - 1] != 'Z') if (zflag && (namlen <= (NAME_SIZE - 2))) { close(fd1); close(fd2); res = zcopy(cbuf1, cbuf2); if (tflag) utime(cbuf2, (struct utimbuf *) & (sp->acctime)); if (res != 0) unlink(cbuf2); /* if error, get rid of the * corpse */ if (vflag && res == 0) printf("Backing up %s\n", cbuf1); return(res); } while (1) { nr = read(fd1, copybuf, COPY_SIZE); if (nr == 0) break; if (nr < 0) { error(NONFATAL, "read error on ", cbuf1, ""); res = EIO; break; } nw = write(fd2, copybuf, nr); if (nw < 0) { if (errno == ENOSPC) { /* Device is full. */ res = OUT_OF_SPACE; break; } /* True write error. */ error(NONFATAL, "write error on ", cbuf2, ""); res = EIO; break; } } if (res == 0) { if (vflag) printf("Backing up %s\n", cbuf1); } else { unlink(cbuf2); } close(fd1); close(fd2); if (tflag) utime(cbuf2, (struct utimbuf *) & (sp->acctime)); return(res); } int zcopy(src, targ) char *src, *targ; { int pid, status, res, s; if ((pid = fork()) < 0) error(FATAL, "cannot fork", "", ""); if (pid > 0) { wait(&status); /* Error codes 0 and 2 are ok, assume others mean disk is full. */ res = (status == 0 || status == NO_SAVINGS ? 0 : OUT_OF_SPACE); return(res); } else { /* Child must execute compress. */ close(1); s = open(targ, O_RDWR); if (s < 0) error(FATAL, "cannot write on ", "targ", ""); execle("/bin/compress", "compress", "-fc", src, (char *) 0, environ); execle("/usr/bin/compress", "compress", "-fc", src, (char *)0,environ); error(FATAL, "cannot exec compress", "", ""); } } copydir(dir1, dir2, namep) char *dir1, *dir2, *namep; { /* Copy a directory. */ int pid, res, status; char fbuf[20], d1buf[MAX_PATH], d2buf[MAX_PATH]; res = 0; if (nflag) return(res); /* backup -n means no directories */ /* Handle directory copy by forking off 'backup' ! */ strcpy(fbuf, "-r"); if (jflag) strcat(fbuf, "j"); if (mflag) strcat(fbuf, "m"); if (sflag) strcat(fbuf, "s"); if (tflag) strcat(fbuf, "t"); if (vflag) strcat(fbuf, "v"); if (zflag) strcat(fbuf, "z"); strcpy(d1buf, dir1); strcat(d1buf, "/", 1); strncat(d1buf, namep, NAME_SIZE); strcpy(d2buf, dir2); strcat(d2buf, "/", 2); strncat(d2buf, namep, NAME_SIZE); if ((pid = fork()) < 0) error(FATAL, "cannot fork", "", ""); if (pid > 0) { wait(&status); return; } else { execle("backup", "backup", fbuf, d1buf, d2buf, (char *) 0, environ); execle("/bin/backup", "backup", fbuf, d1buf, d2buf, (char *)0,environ); execle("/usr/bin/backup","backup",fbuf,d1buf,d2buf,(char *)0,environ); error(FATAL, "cannot recursively exec backup", "", ""); } } newdisk(dir) char *dir; { /* Ask for a new diskette. A big problem is that this program does not * know which device is being used and where it is mounted on. As an * emergency solution, fork off a shell and ask the user to do the work. */ int pid, status; printf("\nDiskette full. Please do the following:\n"); printf(" 1. Unmount the diskette using /etc/umount\n"); printf(" 2. Physically replace the diskette by the next one.\n"); printf(" 3. Mount the new diskette using /etc/mount\n"); printf(" 4. Type CTRL-D to return to the backup program\n"); if ((pid = fork()) < 0) error(FATAL, "cannot fork", "", ""); if (pid > 0) { wait(&status); maketarget(dir); /* make the directory */ } else { execle("/bin/sh", "sh", "-i", (char *) 0, environ); execle("/usr/bin/sh", "sh", "-i", (char *) 0, environ); error(FATAL, "cannot execute shell to ask for new diskette", "", ""); } } usage() { error(2, "Usage: backup [-djmnstvz] dir1 dir2", "", ""); } error(type, s1, s2, s3) int type; char *s1, *s2, *s3; { fprintf(stderr, "backup: %s%s%s\n", s1, s2, s3); if (type == NONFATAL) return; else exit(type); }
C
#include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include "Estructura.h" eEmpleado* eEmpleado_nuevo(void) { eEmpleado* pNuevo = (eEmpleado *)malloc(sizeof(eEmpleado)); return pNuevo; } eEmpleado* eEmpleado_nuevoParametrizado(char* idStr, char* nombreStr, char* direccionStr, char* horasTrabajadasStr, char* sueldoStr) { eEmpleado* peEmpleado = NULL; int id; int horasTrabajadas; int sueldo; if(idStr != NULL && nombreStr != NULL && direccionStr!= NULL && horasTrabajadasStr != NULL && sueldoStr != NULL) { peEmpleado = eEmpleado_nuevo(); if(peEmpleado != NULL) { id = atoi(idStr); horasTrabajadas = atoi(horasTrabajadasStr); sueldo = atoi(sueldoStr); eEmpleado_setId(peEmpleado, id); eEmpleado_setNombre(peEmpleado, nombreStr); eEmpleado_setDireccion(peEmpleado, direccionStr); eEmpleado_setHorasTrabajadas(peEmpleado, horasTrabajadas); eEmpleado_setSueldo(peEmpleado, sueldo); } } return peEmpleado; } void eEmpleado_eliminar(eEmpleado* this) { if(this != NULL) { free(this); } } int eEmpleado_setId(eEmpleado* this,int id) { if(this != NULL) { this->id = id; return 0; } return 1; } int eEmpleado_getId(eEmpleado* this,int* id) { if(this != NULL && id != NULL) { *id = this->id; return 0; } return 1; } int eEmpleado_setNombre(eEmpleado* this,char* nombre) { if(this != NULL && nombre != NULL) { strcpy(this->nombre, nombre); return 0; } return 1; } int eEmpleado_getNombre(eEmpleado* this,char* nombre) { if(this != NULL && nombre != NULL) { strcpy(nombre, this->nombre); return 0; } return 1; } int eEmpleado_getDireccion(eEmpleado* this, char* direccion) { if(this != NULL && direccion != NULL) { strcpy(direccion, this->direccion); return 0; } return 1; } int eEmpleado_setDireccion(eEmpleado* this, char* direccion) { if(this != NULL && direccion != NULL) { strcpy(this->direccion, direccion); return 0; } return 1; } int eEmpleado_setHorasTrabajadas(eEmpleado* this,int horasTrabajadas) { if(this != NULL) { this->horasTrabajadas = horasTrabajadas; return 0; } return 1; } int eEmpleado_getHorasTrabajadas(eEmpleado* this,int* horasTrabajadas) { if(this != NULL && horasTrabajadas != NULL) { *horasTrabajadas = this->horasTrabajadas; return 0; } return 1; } int eEmpleado_setSueldo(eEmpleado* this,int sueldo) { if(this != NULL) { this->sueldo = sueldo; return 0; } return 1; } int eEmpleado_getSueldo(eEmpleado* this,int* sueldo) { if(this != NULL && sueldo != NULL) { *sueldo = this->sueldo; return 0; } return 1; } int eEmpleado_print(eEmpleado* this) { if(this != NULL) { printf("%5d | %15s | %30s | %20d\n", this->id, this->nombre, this->direccion, this->horasTrabajadas); return 0; } return 1; } int eEmpleado_compararNombre(void* this, void* thisDos) { int retorno; eEmpleado* peEmpleado = NULL; eEmpleado* peEmpleadoDos = NULL; if(this != NULL && thisDos != NULL) { peEmpleado = (eEmpleado*)this; peEmpleadoDos = (eEmpleado*)thisDos; retorno = strcmp(peEmpleado->nombre, peEmpleadoDos->nombre); } return retorno; } int eEmpleado_calcularSueldo(void* this) { eEmpleado* peEmpleado = NULL; int retorno = -1; int horasTrabajadas; int cantidad = 0; int cantidadDos = 0; int cantidadTres = 0; int sueldo; if(this != NULL) { peEmpleado = (eEmpleado *)this; eEmpleado_getHorasTrabajadas(peEmpleado, &horasTrabajadas); if(horasTrabajadas <= 120) { cantidad = horasTrabajadas * 180; } if(horasTrabajadas <= 160) { cantidad = 120 * 180; cantidadDos = (horasTrabajadas - 120) * 240; } if(horasTrabajadas <= 240) { cantidad = 120 * 180; cantidadDos = 40 * 240; cantidadTres = (horasTrabajadas - 160) * 350; } sueldo = cantidad + cantidadDos + cantidadTres; peEmpleado->sueldo = sueldo; } return retorno; }
C
#include <stdio.h> #include <assert.h> // calculate_mode возвращает моду из массива а. // вместо точки с запятой открывайте фигурные скобки и пишите ваше решение. int calculate_mode(int n, int a[n]){ int count1 = 0; int count2 = 0; int moda = a[0]; int std = 0; int g = 0; int j; int i; for( j = 0; j < n; j++){ g = a[j]; for (i= 0;i<n;i++){ if(g == a[i]) count1 ++; } if(count1 > count2 ){ moda = a[j]; count2 = count1; } else if(count1 >= count2 && moda < a[j] ){ moda = a[j]; count2 = count1; } count1 = 0; } return moda; } void test_calculate_mode() { assert(calculate_mode(1, (int[]){1}) == 1); assert(calculate_mode(2, (int[]){1,-1}) == 1); assert(calculate_mode(3, (int[]){1,2,3}) == 3); assert(calculate_mode(3, (int[]){0,0,0}) == 0); assert(calculate_mode(5, (int[]){1,2,3,3,4}) == 3); assert(calculate_mode(6, (int[]){1,1,2,2,3,4}) == 2); assert(calculate_mode(10, (int[]){1,12,-3,-3,12,-3,1,4,-3,4}) == -3); printf("Тесты прошли успешно!\n"); } int main() { test_calculate_mode(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemy_action.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: user42 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/27 17:04:12 by flavio #+# #+# */ /* Updated: 2021/09/20 11:51:25 by user42 ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/so_long.h" static void change_active(t_game *game, t_enemy *enemy) { if (enemy->active < 2) enemy->active += 1; else enemy->active = 0; new_fireball(game, enemy->x, enemy->y); } static void enemy_animation(t_game *game, t_enemy *enemy) { if (enemy->going_up) { if (enemy->frame <= 0) { change_active(game, enemy); enemy->going_up = 0; } else enemy->frame -= .6; } else { if (enemy->frame > 7) enemy->going_up = 1; else enemy->frame += .6; } } int is_on_map(int x, int y, t_game *game) { int is_on_map; is_on_map = 1; if (!(x >= game->map.x && x < game->map.x + game->width)) is_on_map = 0; if (!(y >= game->map.y && y < game->map.y + game->height)) is_on_map = 0; return (is_on_map); } static void draw_enemy(t_enemy *enemy, t_game *game) { int i; int x; int y; int w; t_enemy cpy; i = enemy->active; x = ((enemy->x - game->map.x) * BLOCK_SIZE); y = (((enemy->y - game->map.y) * BLOCK_SIZE)) - enemy->frame; if (is_on_map(enemy->x + 1, enemy->y, game)) w = enemy->sprites[i].w; else w = BLOCK_SIZE; copy_img_to(&game->map.map, &enemy->sprites[i], to_array(x, y, w, enemy->sprites[i].h)); } void render_enemies(t_game *game) { t_enemy *enemy; enemy = game->enemies; while (enemy) { if (is_on_map(enemy->x, enemy->y, game)) { draw_enemy(enemy, game); } enemy_animation(game, enemy); enemy = enemy->next; } }
C
#include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <memory.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <grp.h> #include <assert.h> #include <signal.h> //напечатать информацию о группе void printGroupInfo(gid_t gid) { struct group *group_ = getgrgid(gid); if(!group_) { perror("getGroupError"); return; } printf("gid = %d\ngroup name = %s\n", group_->gr_gid, group_->gr_name); } void printProcInfo() { //id текущего процесса pid_t pid = getpid(); //id родительского процесса pid_t ppid = getppid(); printf("pid = %d\nppid = %d\n", pid, ppid); //id сеанса pid_t sid = getsid(0); //id группы процессов pid_t pgrp = getpgrp(); printf("sid = %d\npgrp = %d\n", sid, pgrp); //id реального пользователя uid_t uid = getuid(); printf("uid = %d\n", uid); //id реального пользователя (группы) printf("---real group--\n"); printGroupInfo(getgid()); //id эффективного пользователя uid_t euid = geteuid(); printf("euid = %d\n", euid); //id эффективного пользователя (группы) printf("---effective group---\n"); printGroupInfo(getegid()); } int main() { //13.1 //создадим новый процесс pid_t id = fork(); //если создать не удалось if(id == -1) { perror("fork error"); } //выведем инфу о дочернем if(!id) { //дочерний printf("---children---\n"); printProcInfo(); } else { int res = waitpid(id, 0, 0); if(res == -1) { perror("waitpid error"); return 1; } printf("\n---parent---\n"); printProcInfo(); return 0; } }
C
#include<stdio.h> #include<stdlib.h> void displays(int vin, float dist, float elapsed_time, float *ave_speed) { *ave_speed = dist/elapsed_time; printf("Vehicle ID: %d\n", vin); printf("Distance : %f km \n", dist); printf("Elapsed time: %f hours\n ", elapsed_time); printf("Average speed: %f km/h\n", *ave_speed); } void classification(float speed) { if(speed<70.0){ printf("Slow\n"); }else if(speed>=70.0 && speed<=110.0){ printf("Normal\n"); }else if(speed>110.0){ printf("Fast!\n"); }else{ printf("Invalid input\n"); } } struct vehicle{ int vin; float dist; float timed; }; int main() { //struct vehicle group1[3]; struct vehicle *group1; /*Allocate memory*/ group1 = (struct vehicle *)malloc(3*sizeof(struct vehicle) ); int vin; float dist; float elapsed_time; float ave_speed; vin = 1900110; dist = 100.0; elapsed_time = 1.0; ave_speed = 0.0; /*Initiate data for all vehicle*/ for(int i=0; i<10; ++i){ group1[i].vin = vin; group1[i].dist = dist; group1[i].timed = elapsed_time; } /*Input data manually*/ for(int i=0; i<3; ++i){ printf("Input vehicle ID:\n"); scanf("%d", &vin); printf("Input distance travelled:\n"); scanf("%f", &dist); printf("Input elapsed time:\n"); scanf("%f", &elapsed_time); group1[i].vin = vin; group1[i].dist = dist; group1[i].timed = elapsed_time; } displays(vin, dist, elapsed_time, &ave_speed); classification(ave_speed); }
C
#include <sys/types.h> //Basic System Data types #include <sys/socket.h> // Structure needed by socket #include <netinet/in.h> //sockaddr_in() and other internet definitions #include <arpa/inet.h> //inet(3) functions #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> int main() { int sock, connected, bytes_received , true = 1,i,t1,t2,t3,choice=1; char read_data [1024], received_data[1024],buffer[20]; struct sockaddr_in server_addr,client_addr; int sin_size; printf("\n----------FILE TRANSFER SERVER----------\n"); if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); } else{ printf("\nSocket created successfully\n"); } if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1) { perror("Setsockopt"); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(8888); server_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(server_addr.sin_zero),8); if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))== -1) { perror("Unable to bind"); exit(1); }else{ printf("\nBind successful\n"); } if (listen(sock, 5) == -1) { perror("Listen"); exit(1); }else{ printf("\nListen successful\n"); } printf("\n TCP Server Waiting for client"); fflush(stdout); int s =sizeof(struct sockaddr_in); connected = accept(sock,(struct sockaddr *)&server_addr,&s); bytes_received = recv(connected,received_data,1024,0); FILE *fp; fp = fopen("receive.txt","w+"); fwrite(received_data,1,1024,fp); fseek(fp, 0, SEEK_SET); fread(read_data,1,1024,fp); printf("\nData in receive.txt is : %s\n",read_data); fclose(fp); close(sock); return 0; }
C
#include "ft_ls.h" void read_filesystem(char *direct, char **files, char **directories, char *flags) { DIR *dir; struct dirent *entry; char temp[1024]; int f; int d; f = 0; d = 0; ft_bzero(temp, 1024); if (!(dir = opendir(direct))) exit(1); while ((entry = readdir(dir)) != NULL) { if ( entry->d_name[0] != '.' || ft_strchr(flags, 'a')) { ft_strcpy(temp, direct); ft_strcat(temp, "/"); ft_strcat(temp, entry->d_name); files[f++] = ft_strdup(temp); if (entry->d_type == DT_DIR) directories[d++] = ft_strdup(temp); } } files[f] = NULL; directories[d]= NULL; closedir(dir); } void free_array(char **array) { while(*array) free(*array++); } void recurse(char *direct, char *flags) { char *files[1024]; char *directories[1024]; char subdir[1024]; int d; ft_bzero(subdir, 1024); read_filesystem(direct, files, directories, flags); ft_sort(files, flags); ft_sort(directories, flags); ft_print(files, flags); if (ft_strchr(flags, 'R')) { d = 0; while (directories[d]) { if (!ft_strequ(ft_strrchr(directories[d], '/'),"/.") && !ft_strequ(ft_strrchr(directories[d], '/'), "/..")) { ft_putendl(""); ft_putendl(directories[d]); recurse(directories[d], flags); } d++; } } free_array(files); free_array(directories); }
C
#include"stdio.h" void main() {int b,c,n,i=1,j=1; printf("һΪĸÿÿո"); scanf("%d",&n); scanf("%d,",&c); while(i<=n-1) {scanf("%d,",&b);if(b<c) {c=b;j=i+1;} i++; } printf("\n\nmin is %d\nand it is the %d one\n\n",c,j); }
C
// 11. Crie um aplicativo de conversão entre as temperaturas Celsius e Farenheit.Primeiro o usuário deve escolher se // vai entrar com a temperatura em Célsius ou Farenheit, depois a conversão escolhida é realizada através de um comando SWITCH. // Se C é a temperatura em Célsius e F em farenheit, as fórmulas de conversão são : C = 5.(F - 32) / 9 F = (9.C / 5) + 32 #include <stdio.h> #include <stdlib.h> #include <locale.h> int main(void) { char convert; float Celsius, Farenheit; setlocale(LC_ALL, "portuguese"); do { printf("\t Conversão entre as temperaturas Celsius e Farenheit \n\n"); printf("\t Tecle 'F' para converter Celsius em Farenheit "); printf("\n\t ou tecle 'C' para converter Farenheit em Celsius "); printf("\n\n \t Tecle 'q' para sair "); scanf(" %c", &convert); switch (convert) { case 'F': printf("\t Entre com a temperatura em Celsius: "); scanf("%f", &Celsius); printf("\t A temperatura correspondente em Farenheit são: %.2f \n\n", ((1.8 * Celsius) + 32)); system("pause"); system("cls || clear"); break; case 'C': printf("\t Entre com a temperatura em Farenheit: "); scanf("%f", &Farenheit); printf("\t A temperatura correspondente em Celsius são: %.2f \n\n", ((Farenheit - 32) / 1.8)); system("pause"); system("cls || clear"); break; case 'q': printf("\t Encerrando !!! \n"); break; default: //system("cls || clear"); printf("\n\t\t Tecle o caracter 'F' ou 'C' \n\n"); system("pause"); system("cls || clear"); break; } } while (convert != 'q'); }
C
#include <FS.h> #include <SPIFFS.h> #include <ArduinoJson.h> //Variables DynamicJsonDocument config(3500); bool setupFile(){ log_i("begin filesystem SPIFFS"); if (!SPIFFS.begin(true)) { log_e("SPIFFS Mount Failed"); printOledTextSingleLine("Falha ao montar SPIFFS"); return false; } log_i("begin filesystem completed"); return true; } bool fileExist(fs::FS &fs, const char *dirname, const char *filename, uint8_t levels) { log_i("if file exists: directory -> %s | filename -> %s",dirname,filename); bool exist = false; File root = fs.open(dirname); if (!root) { log_w("Failed to open directory"); printOledTextSingleLine("Falha ao abrir deretório"); return exist; } if (!root.isDirectory()) { log_i("Not a directory"); printOledTextSingleLine("Não é um diretório"); return exist; } File file = root.openNextFile(); while (file) { log_d("found file %s looking for %s",file.name(),filename); exist = strcmp(file.name(), filename) == 0; if (exist) break; file = root.openNextFile(); } log_d("file exist -> %d",exist); return exist; } void listDir(fs::FS &fs, const char *dirname, uint8_t levels) { log_d("Listing directory: %s", dirname); Serial.printf("Listing directory: %s\n", dirname); File root = fs.open(dirname); if (!root) { log_w("Failed to open directory"); printOledTextSingleLine("Falha ao abrir diretírio"); return; } if (!root.isDirectory()) { log_i("Not a directory"); printOledTextSingleLine("Não é um diretório"); return; } File file = root.openNextFile(); while (file) { if (file.isDirectory()) { log_d("found directory %s",file.name()); if (levels) listDir(fs, file.name(), levels - 1); } else { log_d("found file %s %f",file.name(),file.size()); } file = root.openNextFile(); } } String readFile(fs::FS &fs, const char *path) { log_d("Reading file: %s", path); File file = fs.open(path); if (!file || file.isDirectory()) { log_e("Failed to open file for reading"); printOledTextSingleLine("Falha ao ler o arquivo"); return ""; } String out; while (file.available()) out += (char)file.read(); return out; } void writeFile(fs::FS &fs, const char *path, const char *message) { log_d("Writing file: %s", path); File file = fs.open(path, FILE_WRITE); if (!file) { log_e("Failed to open file for writing"); printOledTextSingleLine("Falha ao escrever o arquivo"); return; } if (file.print(message)) { log_i("file written"); } else { log_e("Write failed"); file.close(); SPIFFS.format(); } } void appendFile(fs::FS &fs, const char *path, const char *message) { log_d("appending to file: %s | %s", path, message); File file = fs.open(path, FILE_APPEND); if (!file) { printOledTextSingleLine("Falha ao acrescentar info ao arquivo"); return; } if (file.print(message)) { log_i("message appended to file"); } else { log_e("failed to append message to file"); printOledTextSingleLine("Falha ao escrever arquivo"); } } void renameFile(fs::FS &fs, const char *path1, const char *path2) { log_d("renaming file %s to %s", path1, path2); if (fs.rename(path1, path2)) { log_i("file were renamed"); printOledTextSingleLine("Arquivo Renomeado"); } else { log_e("failed to rename file"); printOledTextSingleLine("Falha ao renomear"); } } void deleteFile(fs::FS &fs, const char *path) { log_d("Deleting file: %s\n", path); if (fs.remove(path)) { log_d("file deleted"); printOledTextSingleLine("Arquivo Removido"); } else { log_e("failed to delete file"); printOledTextSingleLine("Falha ao remover arquivo"); } }
C
#include<stdio.h> int main(void) { char str[80], *pstr; int i, j, k, m, e10, digit, ndigit, a[80], *pa; printf("Input a string:\n"); /*********Found************/ gets(str); printf("\n"); pstr = &str[0]; /* ַָpstrstr׵ַ */ /*********Found************/ pa = a; /* ָpaa׵ַ */ ndigit = 0; /* ndigitжٸ */ i = 0; /* ַеnַ */ j = 0; /* ֵλ */ while (1) { if ((*(pstr + i) >= '0') && (*(pstr + i) <= '9')) { j++; } else { if (j > 0) { /*********Found************/ digit = *(pstr + i - 1) - '0'; /* λdigit */ k = 1; while (k < j) /* λϵλֵۼdigit */ { e10=1; for (m=1; m<=k; m++) { e10=e10*10; /* e10λӦ˵ */ } digit = digit + (*(pstr + i - 1 - k) - '0') * e10; /* λֵۼdigit */ k++; /* λk */ } /*********Found************/ *pa = digit; /* ֵa */ ndigit++; pa++; /* ָpaָaһԪ */ j = 0; } } if ('\0' == *(pstr + i)) { break; } i++; } printf("There are %d numbers in this line.They are:\n", ndigit); for(j=0; j<ndigit; j++) /* ʾ */ { printf("%d ", a[j]); } printf("\n"); return 0; }
C
#include <stdio.h> int main() { int arr[10] = { 5, 10, -1, -4, 7, 9, 2, 3, 20, 15 }; int arrsize = sizeof(arr) / sizeof(int); int min = 0, i, j; for (i = 0, j = 1; i < arrsize; i++, j++) { int t = j; while (t < arrsize) { if (arr[min] > arr[t]) min = t; t++; } int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } printf("ARRAY PRINT\n"); for (int i = 0; i < arrsize; i++) printf("%3d", arr[i]); printf("\n"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> //int main() //{ // int n = 0; // scanf("%d", &n); // int i = 0; // int x = 0; // int count = 0; // int a[50] = { 0 }; // for (i = 0; i < n; i++) // { // scanf("%d", &a[i]); // } // scanf("%d", &x); // for (i = 0; i < n; i++) // { // if (a[i] == x) // { // count++; // } // } // printf("%d", count); // return 0; //} //int main() //{ // int arr[101] = { 0 }; // int n = 0; // scanf("%d", &n); // int i = 0; // for (i = 0; i<n; i++) // { // int m = 0; // scanf("%d", &m); // arr[m]++; // } // int x = 0; // scanf("%d", &x); // printf("%d", arr[x]); // return 0; //} //int main() //{ // int n = 0; // scanf("%d", &n); // int i = 0; // int tmp = 0; // int a[1001] = { 0 }; // for (i = 0; i < n; i++) // { // scanf("%d", &tmp); // a[tmp] = tmp; // } // for (i = 0; i < 1001; i++) // { // if (a[i] != 0) // { // printf("%d",a[i]); // } // } // return 0; //}
C
#ifndef REDBLACK_H #define REDBLACK_H #include "../nstl-types.h" #define destroy_rb(RB) destroy_rb1(RB) #define destroy_rb(RB,D) destroy_rb2(RB,D) /* * A node with a payload pointer. Can be used for regular trees and map * lookups. Can be used for a key/value structure */ struct Red_black; typedef struct Red_black Red_black; /* * Initialize a new red black tree and saves its comparator. */ extern Red_black* redblack( cmp lt ); /* * Inserts a new key into the tree */ extern void rb_insert( Red_black*, void*, void* ); /* * Inserts a new key into the tree with an associated value. Maintains a * uniqueness property - any duplicate key will not be added to the tree. */ extern void rb_insert_unique( Red_black*, void*, void* ); /* * Removes the approperiate node from the tree and returns its payload. * Returns NULL if it is not in the tree. */ extern void* rb_remove( Red_black*, void* key ); /* * Returns the payload of the node with the given key. Returns NULL if key is * not in the tree. */ extern void* rb_get( Red_black*, void* key ); /* * Destroys the red-black tree and frees all its data. * If destroy_associative is NULL, free is called at both key and element. If * either of the FPs are NULL then free will be called on their respective * objects. Otherwise the respective element will be given to the approperiate * destructor function. Returns NULL. */ extern void* destroy_rb( Red_black*, destroy_associative* ); #endif //REDBLACK_H
C
#include <stdio.h> #include <stdlib.h> void ShellSort(int* a, size_t n, size_t h) { int i, j, t; for (i = h; i < n; ++i) { j = i; t = a[i]; while (j >= h && t < a[j - h]) { a[j] = a[j - h]; j -= h; } a[j] = t; } } int main() { int n; scanf("%d", &n); int* a = (int*)(malloc(sizeof(int) * n)); int* h = (int*)(malloc(sizeof(int) * n)); int i; for (i = 0; i < n; ++i) { scanf("%d", &a[i]); } i = 0; h[i] = 1; while (h[i] <= n) { i++; h[i] = h[i - 1] * 2 + 1; } int j; for (j = i - 1; j >= 0; --j) { printf("%d ", h[j]); ShellSort(a, n, h[j]); } printf("\n"); for (i = 0; i < n; ++i) { printf("%d ", a[i]); } free(a); return 0; }
C
#include "futils.h" #include <stdio.h> #include <stdlib.h> bool read_file_to_buffer(const char* filename, char** buffer, size_t* len) { if (!(buffer && len)) { return false; } bool result = false; size_t string_size = 0, read_size = 0; FILE* file = fopen(filename, "r"); if (file) { fseek(file, 0, SEEK_END); long tell = ftell(file); if (tell < 0) { goto exit; } string_size = (size_t)tell; rewind(file); char* mem = (char*)malloc(string_size + 1); if (mem == NULL) { goto exit; } read_size = fread(mem, sizeof(char), string_size, file); mem[read_size] = '\0'; *buffer = mem; *len = read_size; result = true; } else { return false; } exit: fclose(file); return result; }
C
#include <stdio.h> #define BITS_IN_INT (int)sizeof(int) * 8 /*--------------------------------------------------------- convert_2_binary: inserts the binary value of the decimal into an array Takes 2 arguments: -a size 32 int array for holding 1s and 0s -a decimal int that is to be converted to binary -----------------------------------------------------------*/ void convert_2_binary(int binary_holder[], int decimal){ int i; for(i = 0; i < BITS_IN_INT; i++){ binary_holder[i] = decimal >> (BITS_IN_INT - 1); if(binary_holder[i] == -1)binary_holder[i] =1; decimal <<= 1; } } /*--------------------------------------------------------- clear array: sets all values of the array to 0 Takes 1 argument: -an integer array -----------------------------------------------------------*/ void clear_array(int array[]){ int x; for(x = 0; x < BITS_IN_INT; x++){ array[x] = 0; } } /*--------------------------------------------------------- print_binary: prints out value from integer array. Will not print values until it first encounters a non-zero value Takes 1 argument: -a size 32 int array for holding 1s and 0s -----------------------------------------------------------*/ void print_binary(int binary_array[]){ int i = 0; while(!binary_array[i])i++; for(i; i < BITS_IN_INT; i++){ printf("%d",binary_array[i]); } printf("\n"); clear_array(binary_array); }
C
#include <stdio.h> char* myitoa(int n, char* str); char* myitoa(int n, char* str) { int i = 0, temp; int dec = 1, count = 1;//因为求余时个位数也需要算进去,所以count得从1开始 if(n < 0) { str[i++] = '-'; n = -n; } temp = n; do { dec *= 10; temp /= 10; count++; }while(temp > 10); // printf("temp = %d\n",temp); while(count--) { str[i++] = n / dec + '0'; n = n % dec; dec /= 10; } str[i] = '\0'; return str; } int main() { char str[10]; printf("%s\n",myitoa(520, str)); printf("%s\n",myitoa(-1234, str)); return 0; }
C
#include "../include/string.h" void *memset(void *dst, int c, size_t sz) { while (--sz >= 0) *((int*)dst+sz) = c; return dst; } int memcmp(void *s1, void *s2, size_t sz) { }
C
#include<stdlib.h> #include<stdio.h> // using namespace std; struct node{ float coeff; int expo; struct node * link; }; struct node* insert(struct node* head,float co,int ex) { struct node* temp; struct node*newP=malloc(sizeof(struct node)); newP->coeff =co; newP->expo=ex; newP->link=NULL; if(head==NULL || ex>head->expo) { newP->link=head; head=newP; } else{ temp=head; while (temp->link!=NULL && temp->link->expo>=ex) { temp=temp->link; } newP->link=temp->link; temp->link=newP; } return head; } void print(struct node* head) { if(head==NULL) { printf("empty list"); } else{ struct node* temp=head; while (temp!=NULL) { printf("(%.1fx^%d)",temp->coeff,(int) temp->expo); temp=temp->link; if(temp!=NULL) { printf("+"); } else { printf("\n"); } } } } void polyAdd(struct node* head1,struct node* head2) { struct node* ptr1=head1; struct node* ptr2=head2; struct node* head3=NULL; while (ptr1!=NULL && ptr2!=NULL) { if(ptr1->expo == ptr2->expo) { head3=insert(head3,ptr1->coeff + ptr2->coeff,ptr1->expo); ptr1=ptr1->link; ptr2=ptr2->link; } else if(ptr1->expo >ptr2->expo) { head3=insert(head3,ptr1->coeff,ptr1->expo); ptr1=ptr1->link; } else if (ptr1->expo <ptr2->expo) { head3=insert(head3,ptr2->coeff,ptr2->expo); ptr2=ptr2->link; } } while(ptr1!=NULL) { head3=insert(head3,ptr1->coeff,ptr1->expo); ptr1=ptr1->link; } while(ptr2!=NULL) { head3=insert(head3,ptr2->coeff,ptr2->expo); ptr2=ptr2->link; } printf("Added polynomial is : "); print(head3); } struct node* create(struct node* head) { int n,i; float coeff; int expo; printf("enter the num of terms: "); scanf("%d",&n); for(i=0;i<n;i++) { printf("enter the coeff for %d:",i+1); scanf("%f",&coeff); printf("enter the expo for %d:",i+1); scanf("%d",&expo); head=insert(head,coeff,expo); } return head; } int main() { struct node* head1=NULL; struct node* head2=NULL; printf("enter the first polynomial\n"); head1=create(head1); printf("enter the second polynomial\n"); head2=create(head2); polyAdd(head1,head2); return 0; }
C
/* * Host Dispatcher Shell Project for SOFE 3950U / CSCI 3020U: Operating Systems * * Copyright (C) 2015, <GROUP MEMBERS> * All rights reserved. * */ #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include "queue.h" #include "utility.h" #include "hostd.h" #include <string.h> #include <ctype.h> // Put macros or constants here using #define #define MEMORY 1024 #define RESERVED_MEMORY 64 // Put global environment variables here int total_mem = MEMORY - RESERVED_MEMORY; node_t *dispatch_list; node_t *priority1; node_t *priority2; node_t *priority3; node_t *user_jobs; node_t *realtime; int dispatcher_time = 0; node_t *active = NULL; int status = 0; char *processArgv[] = {"./process", NULL}; // Define functions declared in hostd.h here void print_process(proc process) { printf("-------------------------------------------------------------------------------------\n"); printf("PID: %d\tPRIORITY: %d\tTIME: %d\t\tMEMORY: %d\tSIZE: %d\n", process.pid, process.priority, process.processor_time, process.memory_index, process.MBytes); printf("#PRINTERS: %d\t#SCANNERS: %d\tMODEMS: %d\tCDs: %d\n", process.res.num_printers, process.res.num_scanners, process.res.num_modems, process.res.num_CDs); printf("-------------------------------------------------------------------------------------\n"); } void load_dispatch(char *dispatch_file) { FILE * file = fopen(dispatch_file, "r"); while (!feof(file)) { int size = 8; int *info = malloc(sizeof(int) * size); int i = 0; while(!feof(file) && i < size) { char number[] = "\0\0\0\0"; char d = '\0'; int n = 0; while (!feof(file) && isdigit(d = fgetc(file))) { number[n++] = d; } if (strlen(number) > 0) { info[i++] = atoi(number); } if(d == '\n') { break; } } if (i < size) { free(info); info = NULL; } proc process; process.pid = 0; process.arrival_time = info[0]; process.priority = info[1]; process.processor_time = info[2]; process.MBytes = info[3]; process.suspended = false; process.res.num_printers = info[4]; process.res.num_scanners = info[5]; process.res.num_modems = info[6]; process.res.num_CDs = info[7]; dispatch_list = push(dispatch_list, process); } } void add_queue(proc process) { if (process.priority == 0) realtime = push(realtime, process); else if (process.priority == 1) priority1 = push(priority1, process); else if (process.priority == 2) priority2 = push(priority2, process); else if (process.priority == 3) priority3 = push(priority3, process); } int main(int argc, char *argv[]) { // ==================== YOUR CODE HERE ==================== // // Load the dispatchlist char * dispatch_file = NULL; if(argc > 1) dispatch_file = argv[1]; // Add each process structure instance to the job dispatch list queue load_dispatch(dispatch_file); // Iterate through each item in the job dispatch list, add each process // to the appropriate queues dispatcher_time = 0; do { init_res_avail(); node_t *poped; while ( dispatch_list != NULL && seek(dispatch_list)->process.arrival_time <= dispatcher_time) { if (dispatch_list->next != NULL) { poped = pop(dispatch_list); //printf("Time: %d\tPoped: %d\n", dispatcher_time, poped->process.arrival_time); } else { poped = dispatch_list; dispatch_list = NULL; //printf("Time: %d\tPoped: %d\n", dispatcher_time, poped->process.arrival_time); } // Check constrains and add to appro. queue if (poped->process.arrival_time <= dispatcher_time) { if (poped->process.priority == 0) { if (poped->process.MBytes > RESERVED_MEMORY) { printf("Error: Max 64MB for real time job!\n"); } else if (poped->process.res.num_printers > 0 || poped->process.res.num_scanners > 0 || poped->process.res.num_modems > 0 || poped->process.res.num_CDs > 0) { printf("Error: Real time job cannot include any resources!\n"); } else { realtime = push(realtime, poped->process); //printf("pushed: %d\n", poped->process.arrival_time); } } else { if (poped->process.MBytes > total_mem) { printf("Error: Not enough memory!\n"); } else if (poped->process.res.num_printers > NUM_PRINTERS || poped->process.res.num_scanners > NUM_SCANNERS || poped->process.res.num_modems > NUM_MODEMS || poped->process.res.num_CDs > NUM_CDS) { printf("Error: Not enough resources!\n"); } else { user_jobs = push(user_jobs, poped->process); //printf("pushed: %d\n", poped->process.arrival_time); } } } } // Allocate the resources for each process before it's executed while(user_jobs != NULL && check_mem(user_jobs->process.res, user_jobs->process.MBytes) && check_res(user_jobs->process.res)) { user_jobs->process.memory_index = alloc_mem(user_jobs->process.res, user_jobs->process.MBytes); node_t *temp; while( user_jobs != NULL) { if (user_jobs->next != NULL) temp = pop(user_jobs); else { temp = user_jobs; user_jobs = NULL; } alloc_res(temp->process); add_queue(temp->process); } } // Execute the process binary using fork and exec if (active != NULL) { active->process.processor_time--; if (active->process.processor_time == 0) { kill(active->process.pid, SIGINT); waitpid(active->process.pid, &status, WUNTRACED); free_mem(active->process.res, active->process.memory_index, active->process.MBytes); free_res(active->process.res); free(active); active = NULL; } else if (active->process.priority > 0 && !(realtime == NULL && priority1 == NULL && priority2 == NULL && priority3 == NULL)) { kill(active->process.pid , SIGTSTP); waitpid(active->process.pid + 1, &status, WUNTRACED); active->process.suspended = true; if(active->process.priority < 3) { active->process.priority++; } add_queue(active->process); // add back to the queue active = NULL; } } // Pop process by priority. if (active == NULL && !(realtime == NULL && priority1 == NULL && priority2 == NULL && priority3 == NULL)) { if (realtime != NULL) { if (realtime->next != NULL) { active = pop(realtime); } else { active = realtime; realtime = NULL; } } else if (priority1 != NULL) { if (priority1->next != NULL) { active = pop(priority1); } else { active = priority1; priority1 = NULL; } } else if (priority2 != NULL) { if (priority2->next != NULL) { active = pop(priority2); } else { active = priority2; priority2 = NULL; } } else if (priority3 != NULL) { if (priority3->next != NULL) {; active = pop(priority3); } else { active = priority3; priority3 = NULL; } } if(active->process.suspended == true) { kill(active->process.pid, SIGCONT); active->process.suspended = false; } else { pid_t pid; pid = fork(); if (pid < 0) { printf("Error...\n"); } else if (pid == 0) { // child process execvp(processArgv[0], processArgv); } active->process.pid = pid; print_process(active->process); } } sleep(1); dispatcher_time ++; //printf("Time: %d\n", dispatcher_time); } while (active != NULL || !(realtime == NULL && priority1 == NULL && priority2 == NULL && priority3 == NULL) || dispatch_list != NULL); // Perform the appropriate signal handling / resource allocation and de-alloaction // Repeat until all processes have been executed, all queues are empty return EXIT_SUCCESS; }
C
#include "stdio.h" #include "string.h" #include "stdlib.h" #include "unistd.h" #include "miss.h" //栈 Status Stack_Init(STACK *obj,unsigned int deep) { obj->data = (ELEMENT_TYPE*)malloc(sizeof(ELEMENT_TYPE)*deep); memset(obj->data,0,sizeof(ELEMENT_TYPE)*deep); if(obj->data != NULL) { obj->data = obj->end = obj->data; obj->top = obj->data+(deep)*sizeof(ELEMENT_TYPE); } else return OVERFLOW; } Status Stack_Push(STACK *obj,ELEMENT_TYPE data) { if(obj->data != obj->top) { *(obj->data) = data; obj->data++; } else { printf("Stack is full now\r\n"); return OVERFLOW; } return OKAY; } ELEMENT_TYPE Stack_Pop(STACK *obj) { ELEMENT_TYPE ret; if(obj->data != obj->end) { obj->data--; ret = *(obj->data); *(obj->data) = (struct Route){ (unsigned int)0, (unsigned int)0, }; return ret; } else { printf("Stack is empty now\r\n"); return (struct Route){0,0}; } } struct Route my_route={ .pos = pos(1,1),//起点 .dir = Right, //向右 .last_dir = UNKNOW,//上次方向 }; Status Missing_route(void) { unsigned int graph[10][10] = { {1,1,1,1,1,1,1,1,1,1},//0 {1,0,0,1,0,0,0,1,0,1},//1 {1,0,0,1,0,0,0,1,0,1},//2 {1,0,0,0,0,1,1,0,0,1},//3 {1,0,1,1,1,0,0,0,0,1},//4 {1,0,0,0,1,0,0,0,0,1},//5 {1,0,1,0,0,0,1,0,0,1},//6 {1,0,1,1,1,0,1,1,0,1},//7 {1,1,0,0,0,0,0,0,0,1},//8 {1,1,1,1,1,1,1,1,1,1},//9 // 0 1 2 3 4 5 6 7 8 9 }; STACK my_stack; Stack_Init(&my_stack,256); //出口 unsigned char out = pos(8,8); //起点入栈 Stack_Push(&my_stack,my_route); graph[my_route.pos/10][my_route.pos%10] = 1;//走过 //一直找出口 while(my_route.pos != out) { switch (my_route.dir) { case Right:{ if(my_route.last_dir != Left) { if(graph[my_route.pos/10][my_route.pos%10+1])//向右走不通 { my_route.dir = Down; } else { graph[my_route.pos/10][my_route.pos%10] = 2;//走过 my_route.pos += 1;//向右走一步 my_route.last_dir = Right; Stack_Push(&my_stack,my_route); } } else { my_route.dir = Down; } }break; case Down:{ if(my_route.last_dir != Up) { if(graph[my_route.pos/10+1][my_route.pos%10])//向下走不通 { my_route.dir = Left; } else { graph[my_route.pos/10][my_route.pos%10] = 2;//走过 my_route.pos += 10;//向下走一步 Stack_Push(&my_stack,my_route); my_route.dir = Right;//重置状态机 my_route.last_dir = Down; } } else { my_route.dir = Left; } }break; case Left:{ if(my_route.last_dir != Right) { if(graph[my_route.pos/10][my_route.pos%10-1])//向左走不通 { my_route.dir = Up; } else { graph[my_route.pos/10][my_route.pos%10] = 2;//走过 my_route.pos -= 1;//向左走一步 Stack_Push(&my_stack,my_route); my_route.dir = Right; my_route.last_dir = Left; } } else { my_route.dir = Up; } }break; case Up:{ if(my_route.last_dir != Down) { if(graph[my_route.pos/10-1][my_route.pos%10])//向上走不通 { my_route.dir = UNKNOW; } else { graph[my_route.pos/10][my_route.pos%10] = 2;//走过 my_route.pos -= 10;//向上走一步 Stack_Push(&my_stack,my_route); my_route.dir = Right; my_route.last_dir = Up; } } else { my_route.dir = UNKNOW; } }break; default:{ graph[my_route.pos/10][my_route.pos%10] = 1;//死路不走了 my_route = Stack_Pop(&my_stack); my_route.dir++; } break; } usleep(500*1000); printf("now pos:(%d,%d)\tnow dir:%d\r\n",my_route.pos/10,my_route.pos%10,my_route.dir); } printf("SUCCESSFUL!\r\n"); for(int y=0;y<10;y++) { for(int x=0;x<10;x++) { printf("%-2d",graph[y][x]); } printf("\n"); } return OKAY; } int main(void) { Missing_route(); return 0; }
C
/* Kunci Soal M7 by David Fauzi */ // Header #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct // Queue { int front, rear, size; unsigned capacity; int *array; } Queue; // FUNGSI-FUNGSI QUEUE // Membuat queue Queue *createQueue(unsigned capacity) { Queue *queue = (Queue *)malloc(sizeof(Queue)); queue->capacity = capacity; queue->front = queue->size = 0; queue->rear = capacity - 1; queue->array = (int *)malloc(queue->capacity * sizeof(int)); return queue; } // cek kalo queue penuh int isFull(Queue *queue) { return (queue->size == queue->capacity); }; // Cek kalo queue kosong int isEmpty(Queue *queue) { return (queue->size == 0); }; // enqueue/push queue dari rear void enqueue(Queue *queue, int item) { if (isFull(queue)) return; queue->rear = (queue->rear + 1) % queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size + 1; } // dequeue/pop queue dari front void dequeue(Queue *queue) { // asumsi tidak ada kasus queue empty lalu di dequeue int item = queue->array[queue->front]; queue->front = (queue->front + 1) % queue->capacity; queue->size = queue->size - 1; } // fungsi peek (melihat node paling depan tanpa di-dequeue) int front(Queue *queue) { return queue->array[queue->front]; } // Cek indeks dari elemen tertinggi dalam queue int maxIndex(Queue *q, int sortedIndex) { int max_index = -1; int max_val = INT_MIN; int n = q->size; for (int i = 0; i < n; i++) { int curr = front(q); dequeue(q); if (curr >= max_val && i <= sortedIndex) { max_index = i; max_val = curr; } enqueue(q, curr); } return max_index; } // Pindahin elemen tertinggi ke rear void insertMaxToRear(Queue *q, int max_index) { int max_val; int n = q->size; for (int i = 0; i < n; i++) { int curr = front(q); dequeue(q); if (i != max_index) enqueue(q, curr); else max_val = curr; } enqueue(q, max_val); } // Sort queue secara descending void sortQueue(Queue *q) { for (int i = 1; i <= q->size; i++) { int min_index = maxIndex(q, q->size - i); insertMaxToRear(q, min_index); } } // Fungsi solve susunan piringan per day nya void solveTower(int N,int *arr) { int iter,currBottom=N+1,placed; Queue *q = createQueue(N); for (int i = 0; i < N; i++) { printf("Day %d:",i+1); enqueue(q, arr[i]); sortQueue(q); iter = 0; placed=0; while (!isEmpty(q) && iter <= i) { int tower = front(q); if (currBottom-1 == tower) { printf(" "); printf("%d",tower); dequeue(q); currBottom = tower; placed=1; } iter++; } if(!placed) printf(" -"); printf("\n"); } } int main() { int N; printf("Jumlah hari: "); scanf("%d", &N); int *arr = (int*)malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { printf("Ukuran piringan yang diterima di day %d: ",i+1); scanf("%d", &arr[i]); } printf("Tahapan Pembangunan Tower:\n"); solveTower(N,arr); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct { void *buf; unsigned int size; unsigned int head, tail; } dft_buffer; int dft_buffer_init(dft_buffer *, unsigned const int); int dft_buffer_read(dft_buffer *, void *, unsigned const int); int dft_buffer_write(dft_buffer *, void *, unsigned const int); int dft_buffer_pretty(dft_buffer *); int dft_buffer_init(dft_buffer * b, unsigned const int size) { if (!b) return -1; b->buf = malloc(size+1); if(!(b->buf)) return -1; b->size = size+1; b->head = 1; b->tail = 0; return 0; } int dft_buffer_write(dft_buffer * b, void * writebuf, unsigned int count) { unsigned int used; unsigned int i; if(!b || !b->buf || !writebuf) return -1; used = (b->size + b->head - b->tail - 1)%(b->size); if ((used + count) > (b->size-1)) return -1; for(i = 0; i < count; i++) { *((char *)b->buf+b->head) = *((char *)writebuf + i); b->head = (b->head+1)%(b->size); } return 0; } int dft_buffer_read(dft_buffer * b, void * readbuf, unsigned int count) { unsigned int used; unsigned int i; if(!b || !b->buf || !readbuf) return -1; used = (b->size + b->head - b->tail - 1)%(b->size); if(count > used) return -1; for(i = 0; i < count; i++) { *((char *)readbuf + i) = *((char *)b->buf + (b->tail + 1)%(b->size)); b->tail = (b->tail+1)%(b->size); } return 0; } int dft_buffer_pretty(dft_buffer * b) { unsigned int i; if(!b || !b->buf) return -1; for(i = b->tail + 1; i != b->head; i = (i+1)%(b->size)) printf("%c", *((char *)b->buf + i)); return 0; } int main() { const unsigned int s = 20; char b[6] = "asdfg"; int i; dft_buffer abc; dft_buffer_init(&abc, s); printf("tail: %d\thead: %d\n", abc.tail, abc.head); for(i=0; i<s; i++) { printf("write: %d\n", dft_buffer_write(&abc, b, 6)); dft_buffer_pretty(&abc); printf("\ntail: %d\thead: %d\n", abc.tail, abc.head); printf("read: %d\n", dft_buffer_read(&abc, b, 6)); dft_buffer_pretty(&abc); printf("\ntail: %d\thead: %d\n", abc.tail, abc.head); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_unsg.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: daalexan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/23 19:50:22 by daalexan #+# #+# */ /* Updated: 2018/05/23 19:50:33 by daalexan ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdint.h> #include <sys/types.h> #include <stdarg.h> #include "ft_func_handle.h" uintmax_t ft_unsg(va_list *arg, t_arg *blanck) { uintmax_t nbr; nbr = va_arg(*arg, uintmax_t); if (blanck->task == hh) nbr = (unsigned char)nbr; else if (blanck->task == h) nbr = (unsigned short int)nbr; else if (blanck->task == l) nbr = (unsigned long int)nbr; else if (blanck->task == ll) nbr = (unsigned long long int)nbr; else if (blanck->task == j) nbr = (uintmax_t)nbr; else if (blanck->task == z) nbr = (size_t)nbr; else nbr = (unsigned int)nbr; return (nbr); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "biblio.h" /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : Labirinto* LeLabirinto(const char*); Funcao : Recebe o argumento "argv[1]" que contem o labirinto problema e lê e aloca todos os dados contidos neste; Entrada : Recebe um "const char*" que, no caso, é um .txt; Saida : A saída é um tipo Labirinto* pronto pra uso das outras funções −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ Labirinto* LeLabirinto(const char* entrada) { int i = 0, j = 0; char* aux; FILE* arq; Labirinto* lab_aux; arq = fopen(entrada, "rt"); if(arq == NULL){ printf("\n\t Erro ao abrir arquivo!\n"); return NULL; } lab_aux = (Labirinto *)malloc(sizeof(Labirinto)); aux = (char*)malloc(1000*sizeof(char)); fscanf(arq, "%d %d %d %d %d", &(lab_aux->N), &(lab_aux->x), &(lab_aux->y), &(lab_aux->sx), &(lab_aux->sy)); alocaLabirinto(lab_aux); for(i = 0; i < lab_aux->N; i++){ for(j = 0; j < lab_aux->N; j++){ fscanf(arq, "%s", aux); lab_aux->mapa[i][j] = (char)atoi(aux); } } fclose(arq); free(aux); return lab_aux; } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : int CaminhaLabirintoRecursivo(Labirinto*, int, int, int**); Funcao : Calcula/Encontra o caminho que Teseu deverá seguir para encontrar a espada mágica de modo Recursivo; Entrada : Recebe uma estruturado tipo Labirinto*, dois inteiros (x e y) e a matriz de saída (int**); Saida : Retorna um numero inteiro, 1 ou 0. "1" se o caminho até a espada foi encontrado e "0" se não foi; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ int CaminhaLabirintoRecursivo(Labirinto* lab, int x, int y, int** sol) { if (x == lab->sx && y == lab->sy){ sol[x][y] = 1; return 1; } else { if(lab->mapa[x][y] == 0 && sol[x][y] == 0){ sol[x][y] = 1; if((CaminhaLabirintoRecursivo(lab, x + 1, y, sol) == 1)) return 1; if((CaminhaLabirintoRecursivo(lab, x, y + 1, sol) == 1)) return 1; if((CaminhaLabirintoRecursivo(lab, x - 1, y, sol) == 1)) return 1; if((CaminhaLabirintoRecursivo(lab, x, y - 1, sol) == 1)) return 1; sol[x][y] = 0; } } return 0; } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : int CaminhaLabirintoIterativo(Labirinto*, int, int, int**, TipoPilha*) Funcao : Calcula/Encontra o caminho que Teseu deverá seguir para encontrar a espada mágica de modo Iterativo; Entrada : Recebe uma estruturado tipo Labirinto*, dois inteiros (x e y), a matriz de saída (int**) e um TipoPilha*; Saida : Retorna um numero inteiro, 1 ou 0. "1" se o caminho até a espada foi encontrado e "0" se não foi; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ int CaminhaLabirintoIterativo(Labirinto* lab, int x, int y, int** sol, TipoPilha* pilha) { int i = 0, j = 0, k = 0; i = x; j = y; while((i != lab->sx) || (j != lab->sy)) { sol[i][j] = 1; if(i == 0 && j == 0){ // (0,0) if(lab->mapa[i+1][j] == 0){ Empilha(pilha, i, j); i++; } else if(lab->mapa[i][j+1] == 0){ Empilha(pilha, i, j); j++; } } else if(i == 0){ //Borda superior if(lab->mapa[i+1][j] == 0){ Empilha(pilha, i, j); i++; } else if(lab->mapa[i][j+1] == 0){ Empilha(pilha, i, j); j++; } else if(lab->mapa[i][j-1] == 0){ Empilha(pilha, i, j); j--; } } else if(j == 0){ //Borda esquerda if(lab->mapa[i+1][j] == 0){ Empilha(pilha, i, j); i++; } else if(lab->mapa[i][j+1] == 0){ Empilha(pilha, i, j); j++; } else if(lab->mapa[i-1][j] == 0){ Empilha(pilha, i, j); i--; } } else if(i == lab->N-1 && j == lab->N-1){ //(N-1, N-1) if(lab->mapa[i-1][j] == 0){ Empilha(pilha, i, j); i--; } else if(lab->mapa[i][j-1] == 0){ Empilha(pilha, i, j); j--; } } else if(i == lab->N-1){ //Borda inferior if(lab->mapa[i][j+1] == 0){ Empilha(pilha, i, j); j++; } else if(lab->mapa[i-1][j] == 0){ Empilha(pilha, i, j); i--; } else if(lab->mapa[i][j-1] == 0){ Empilha(pilha, i, j); j--; } } else if(j == lab->N-1){ //Borda direita if(lab->mapa[i+1][j] == 0){ Empilha(pilha, i, j); i++; } else if(lab->mapa[i-1][j] == 0){ Empilha(pilha, i, j); i--; } else if(lab->mapa[i][j-1] == 0){ Empilha(pilha, i, j); j--; } } else{ // "Meio" da matriz if(lab->mapa[i+1][j] == 0){ Empilha(pilha, i, j); i++; } else if(lab->mapa[i][j+1] == 0){ Empilha(pilha, i, j); j++; } else if(lab->mapa[i-1][j] == 0){ Empilha(pilha, i, j); i--; } else if(lab->mapa[i][j-1] == 0){ Empilha(pilha, i, j); j--; } } } if(i == lab->sx && j == lab->sy){ Empilha(pilha, i, j); k = pilha->tamanho; while(k > 0){ Desempilha(pilha, sol); k--; } return 1; } else { printf("0\n"); return 0; } } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : void alocaLabirinto(Labirinto*); Funcao : Alocar memória para uma estrutura do tipo Labirinto*; Entrada : Uma estrutura do tipo Labirinto*; Saida : Nao tem saida, aloca o que é necessario e finaliza; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ void alocaLabirinto(Labirinto* lab) { int i; lab->mapa = (unsigned char**)malloc(lab->N * sizeof(unsigned char*)); for(i = 0; i < lab->N; i++) lab->mapa[i] = (unsigned char*)malloc(lab->N * sizeof(unsigned char)); } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : void desalocaLabirinto(Labirinto*); Funcao : Desalocar a memoria alocada em uma estrutura do tipo Labirinto*; Entrada : Uma estrutura do tipo Labirinto*; Saida : Nao tem saida, desaloca tudo que está alocado no Labirinto* e finaliza; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ void desalocaLabirinto(Labirinto* lab) { int i = 0; for(i = 0; i < lab->N; i++) free(lab->mapa[i]); free(lab->mapa); free(lab); } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : void PilhaVazia(TipoPilha*); Funcao : Criar uma pilha vazia, alocando os espaços necessarios e setando o tamanho para zero; Entrada : Uma estrutura do TipoPilha*; Saida : Não tem saída, aloca tudo que é necessario para uma pilha e finaliza; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ void PilhaVazia(TipoPilha* pilha) { pilha->Topo = (Apontador)malloc(sizeof(TipoCelula)); pilha->Fundo = pilha->Topo; pilha->Topo->prox = NULL; pilha->tamanho = 0; } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : void Empilha(TipoPilha*, int, int); Funcao : Coloca as coordenadas recebidas em um TipoCelula* que ficará no topo da pilha, muda a posição do "Topo" e aumenta o contador de tamanho da pilha; Entrada : Recebe uma estrutura do TipoPilha* e dois inteiros (coordenadas); Saida : Não tem saída, empilha o que tiver de ser empilhado e finaliza; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ void Empilha(TipoPilha* pilha, int x, int y) { Apontador Aux; Aux = (Apontador)malloc(sizeof(TipoCelula)); Aux->ponto.i = x; Aux->ponto.j = y; Aux->prox = pilha->Topo; pilha->Topo = Aux; pilha->tamanho++; } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : void Desempilha(TipoPilha*, int**); Funcao : Pega os valores que estão no topo da pilha, coloca as coordenadas na matriz de saída, desempilha (desaloca) o antigo topo e diminui o contador de tamanho da pilha; Entrada : Recebe uma estrutura TipoPilha* e a matriz de saída (int**); Saida : Não tem saída, desempilha a pilha em questão e finaliza; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ void Desempilha(TipoPilha* pilha, int** sol) { int x, y; Apontador auxiliar; auxiliar = pilha->Topo; x = pilha->Topo->ponto.i; y = pilha->Topo->ponto.j; sol[x][y] = 1; pilha->Topo = auxiliar->prox; free(auxiliar); pilha->tamanho--; } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : void desalocaMatrizSaida(Labirinto*, int**); Funcao : Desalocar o espaço alocado para a matriz de saída (int**); Entrada : Uma estrutura tipo Labirinto* e a matriz de saída em questão (int**); Saida : Não tem saída. Desaloca a matriz e finaliza; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ void desalocaMatrizSaida(Labirinto* lab, int** sol) { int i = 0; for(i = 0; i < lab->N; i++) free(sol[i]); free(sol); } /*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Prototipo : int Vazia(TipoPilha*); Funcao : Verificar se a pilha esta vazia ou nao; Entrada : Uma estrutura TipoPilha*; Saida : Um número inteiro. 1 se a pilha estiver vazia, 0 se não estiver; −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/ int Vazia(TipoPilha* pilha) { if(pilha->tamanho == 0) return 1; else return 0; }
C
/* ========================================================================== */ /* Projet : biblClient */ /* -------------------------------------------------------------------------- */ /* client.c : fonctions de gestion du fichier client */ /* -------------------------------------------------------------------------- */ /* Auteur : Michel Gineste */ /* ========================================================================== */ #include <string.h> #include <stdio.h> #include "client.h" /* -------------------------------------------------------------------------- */ /* litClient : lecture d'un enregistrement du fichier client connaissant */ /* la clef (noCli). */ /* */ /* La clef doit etre renseignee avant l'appel. */ /* */ /* Valeur retournee : >0 (numero de l'enregistrement trouve) */ /* 0 (non trouve) */ /* -------------------------------------------------------------------------- */ int litClient(CLIENT* c, FILE* fichier) { CLIENT client; int trouve; int i; /* -------------------------------------------------------------------------- */ /* Boucle de recherche squentielle */ /* -------------------------------------------------------------------------- */ trouve = 0; i = 0; fseek(fichier, i * sizeof(CLIENT), SEEK_SET); fread(&client, sizeof(CLIENT), 1, fichier); while (!feof(fichier) && trouve == 0) { if(strcmp(client.noCli, c->noCli) == 0) { trouve = i + 1; *c = client; } i++; fseek(fichier, i * sizeof(CLIENT), SEEK_SET); fread(&client, sizeof(CLIENT), 1, fichier); } return trouve; } /* -------------------------------------------------------------------------- */ /* ecritClient : mise jour ou ajout dans le fichier client connaissant */ /* la clef (noCli). */ /* */ /* Remplir TOUS les champs avant d'crire ! */ /* */ /* Valeur retournee : >0 (numero de l'enregistrement ecrit) */ /* 0 (non ecrit) */ /* -------------------------------------------------------------------------- */ int ecritClient(CLIENT* c, FILE* fichier) { CLIENT client; int trouve; int i; /* -------------------------------------------------------------------------- */ /* Boucle de recherche squentielle */ /* -------------------------------------------------------------------------- */ trouve = 0; i = 0; fseek(fichier, i * sizeof(CLIENT), SEEK_SET); fread(&client, sizeof(CLIENT), 1, fichier); while (!feof(fichier) && trouve == 0) { if(strcmp(client.noCli, c->noCli) == 0) { trouve = i + 1; } i++; fseek(fichier, i * sizeof(CLIENT), SEEK_SET); fread(&client, sizeof(CLIENT), 1, fichier); } if (trouve > 0) { fseek(fichier, (trouve - 1) * sizeof(CLIENT), SEEK_SET); fwrite(c, sizeof(CLIENT), 1, fichier); } else { fseek(fichier, i * sizeof(CLIENT), SEEK_SET); fwrite(c, sizeof(CLIENT), 1, fichier); trouve = i; } return trouve; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdlib.h> #include <zconf.h> #include "FileBuffer.h" #define NUM_THREADS 4 #define SIZE_OF_BUFF 5 FileDeq *fileDeq; void writeToFile(FileBuff *buff,void *args) { printf("writing\n"); fprintf(buff->filePtr,"/Hello world! %s\n",(char*)args); } void *threadFunction(void *args) { printf("thread start\n"); doFileBuff(fileDeq,"1.txt",&writeToFile,"Thread one"); freeFileBuff(fileDeq,"1.txt"); int res = 20; pthread_exit(&res); } int main (int argc, char *argv[]) { FileDeq *deq = initializeFileDequeue(SIZE_OF_BUFF); pthread_t thread[NUM_THREADS]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&thread[1], &attr, threadFunction, NULL); pthread_attr_destroy(&attr); printf("main\n"); void **a; int res = pthread_join(thread[1], a); printf("main\n"); pthread_exit(NULL); } // Deq* dequeue = initializeDequeue(); // for (int i = 0; i < 10; ++i) // { // char str[10]; // sprintf(str, "%d", rand()); // FileBuff* buff = initializeFileBuff(str); // addNode(dequeue,buff); // } // printDequeue(dequeue); // pop(dequeue); // pop(dequeue); // pop(dequeue); // printDequeue(dequeue); // long timeOne = (unsigned long)time(NULL); // sleep(2); // long timeTwo = (unsigned long)time(NULL); // printf("Has past %f",difftime(timeOne,timeTwo // )); // // pthread_t thread[NUM_THREADS]; // pthread_attr_t attr; // int rc; // long t; // void *status; // /* Initialize and set thread detached attribute */ // pthread_attr_init(&attr); // pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // // for(t=0; t<NUM_THREADS; t++) { // printf("Main: creating thread %ld\n", t); // rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t); // if (rc) { // printf("ERROR; return code from pthread_create() is %d\n", rc); // exit(-1); // } // } // // /* Free attribute and wait for the other threads */ // pthread_attr_destroy(&attr); // for(t=0; t<NUM_THREADS; t++) { // rc = pthread_join(thread[t], &status); // if (rc) { // printf("ERROR; return code from pthread_join() is %d\n", rc); // exit(-1); // } // printf("Main: completed join with thread %ld having a status of %e\n",t,*((double *)status)); // } // // printf("Main: program completed. Exiting.\n"); // pthread_exit(NULL); //}
C
/* * Program with solution to Ques 9 * Compilation- gcc -o base32_to_base64 base32_to_base64.c * Execution- ./base32_to_base64 * Dushyant Batra, (1910990098), 18/08/2021 * Assignment 3 (Bits and Bytes) */ #include<stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> //returns the character corresponding to given binary representation in base 64. //params: //char* temp: string containing all bits. //int start:the position from where this character in base 64 starts //int end:the position where the character ends. //return char:character corresponding to given binary representation in base 64. char base64(char* temp, int start, int end) { int val = 0; for(int i = start; i < end; i++) { val = val * 2 + (temp[i] - '0'); } if(val < 26) { val = val + 65; } else if(val < 52) { val = val + 71; } else if(val < 62) { val = val - 4; } else if(val == 62) { val = val - 19; } else { val = val - 16; } return val; } //returns binary representation of given integer. //params: //int val: integer value //return char*: string with binary representation of given integer. char* binary_representation(int val) { char* res = (char*)malloc(5*sizeof(int)); int i = 4; while(val > 0) { res[i--] = (val % 2) + '0'; val /= 2; } while(i >= 0) { res[i--] = '0'; } return res; } //returns binary representation of given in character in base 32. //params: //char ch: character in base 32 format //return char*: string with binary representation of given integer. char* base32_to_binary(char ch) { int val; if(ch >= 'A' && ch <= 'Z') { val = ch - 65; } else if(ch >= '2' && ch <= '7') { val = ch - 24; } else { return NULL; } return binary_representation(val); } //prints base 64 string corresponding to given base 32 string //params: //char* str: string in base 32 format //return void void get_base64_from_base32(char* str) { int str_length = strlen(str); char temp[1000] = {'\0'}; for(int i = 0; i < str_length; i++) { char* res = base32_to_binary(str[i]); if(res != NULL) { strcat(temp,res); free(res); } } int binary_length = strlen(temp); binary_length = (binary_length / 8) * 8; temp[binary_length] = '\0'; //variable which stores no. of 0 to be added at end. int pad = binary_length % 6; if(pad != 0) { pad = 6 - pad; } for(int i = 0; i < pad; i++) { strcat(temp,"0"); } //variable which stores no. of = to be added at end. int equals = (strlen(temp) / 6) % 4; if(equals != 0) { equals = 4 - (equals % 4); } for(int i = 0; i < strlen(temp); i += 6) { printf("%c", base64(temp, i , i+6)); } for(int i = 0; i < equals; i++) { printf("="); } printf("\n"); } int main() { int n; scanf("%d",&n); while(n-- > 0) { char str[1000]; scanf("%s",str); get_base64_from_base32(str); } }
C
/** * helpers.c * * Helper functions for Problem Set 3. */ #include <cs50.h> #include <stdio.h> #include "helpers.h" /** * Returns true if value is in array of n values, else false. */ bool search(int value, int values[], int n) { sort(values, n); int min = 0; int max = n - 1; while (max - 1 > min) { if (values[max] == value) { return true; } if (values[min] == value) { return true; } int guess = (max + min) / 2; if (values[guess] == value) { return true; } else if (values[guess] < value) { min = guess ++; } else if (values[guess] > value) { max = guess --; } } return false; } /** * Sorts array of n values. */ void sort(int values[], int n) { int start = 0; while (start < n - 1) { for (int i=0; i < n-1; i ++) { int left = values[i]; int right = values[i + 1]; if (left > right) { values[i] = right; values[i+1] = left; } } start ++; } }
C
#define P 15 #define Q 16 #define F (1 << Q) #define CONVERT_TO_FP(n) ((n) * (F)) #define CONVERT_TO_INT_TOWARD_ZERO(x) ((x) / (F)) #define CONVERT_TO_INT_NEAREST(x) ((x) >= 0 ? ((x) + (F) / 2) / (F) : ((x) - (F) / 2) / (F)) #define ADD(x, y) ((x) + (y)) #define SUB(x, y) ((x) - (y)) #define ADD_INT(x, n) ((x) + (n) * (F)) #define SUB_INT(x, n) ((x) - (n) * (F)) #define MUL(x, y) (((int64_t)(x)) * (y) / (F)) #define MUL_INT(x, n) ((x) * (n)) #define DIV(x, y) (((int64_t)(x)) * (F) / (y)) #define DIV_INT(x, n) ((x) / (n))
C
/* 1: gcc -Wall -ansi -O2 1.c -lpthread 2: ./a.out test1.txt */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <errno.h> #define GRID_W 9 #define GRID_H 9 #define BLOCK_OFFSET 3 #define EXPECTED_SUM (GRID_W * BLOCK_OFFSET) extern int errno; int SUM_THREAD = 0; pthread_mutex_t SUM_THREAD_MUTEX; unsigned short GRID[GRID_H][GRID_W]; pthread_mutex_t GRID_MUTEX[GRID_H][GRID_W]; pthread_t LINE_THREAD[GRID_W]; pthread_t COLUMN_THREAD[GRID_H]; pthread_t BLOCK_THREAD[GRID_H]; void print_grid(){ int height, width; for(height = 0; height < GRID_H; height++){ for(width = 0; width < GRID_W; width++){ printf("%d ", GRID[height][width]); } printf("\n"); } } void load_grid(FILE * file){ int height, width; for(height = 0; height < GRID_H; height++){ for(width = 0; width < GRID_W; width++){ int number = 0; fscanf(file, "%d", &number); GRID[height][width] = number; } } } void init_mutexes(){ int height, width; for(height = 0; height < GRID_H; height++){ for(width = 0; width < GRID_W; width++){ pthread_mutex_init(&GRID_MUTEX[height][width], NULL); } } pthread_mutex_init(&SUM_THREAD_MUTEX, NULL); } void destroy_mutexes(){ int height, width; for(height = 0; height < GRID_H; height++){ for(width = 0; width < GRID_W; width++){ pthread_mutex_destroy(&GRID_MUTEX[height][width]); } } pthread_mutex_destroy(&SUM_THREAD_MUTEX); } int *init_array(int size){ int *a; a = (int*) malloc (size*sizeof(int)); int counter; for(counter = 0; counter < size; counter++){ a[counter] = 0; } return a; } void *check_line(void *arg){ int *array = init_array(GRID_W+1); int counter; int sum = 0; long line = (long) arg; for(counter = 0; counter < GRID_W ; counter++ ){ pthread_mutex_lock (&GRID_MUTEX[line][counter]); unsigned short grid_copy = GRID[line][counter]; pthread_mutex_unlock (&GRID_MUTEX[line][counter]); if(array[grid_copy] == 0){ sum++; } else { printf("LINHA (%lu): %hu duplicado em [%d]!\n", line, grid_copy, counter); } array[grid_copy]++; } if(sum == GRID_W){ printf("LINHA (%lu): Valida!\n", line); pthread_mutex_lock (&SUM_THREAD_MUTEX); SUM_THREAD++; pthread_mutex_unlock (&SUM_THREAD_MUTEX); }else{ printf("LINHA (%lu): Invalida!\n", line); } free(array); pthread_exit((void*) 0); } void *check_column(void *arg){ int *array = init_array(GRID_H+1); int counter; int sum = 0; long column = (long) arg; for(counter = 0; counter < GRID_H ; counter++ ){ pthread_mutex_lock (&GRID_MUTEX[counter][column]); unsigned short grid_copy = GRID[counter][column]; pthread_mutex_unlock (&GRID_MUTEX[counter][column]); if(array[grid_copy] == 0){ sum++; } else { printf("COLUNA (%lu): %hu duplicado em [%d]!\n", column, grid_copy, counter); } array[grid_copy]++; } if(sum == GRID_H){ printf("COLUNA (%lu): Valida!\n", column); pthread_mutex_lock (&SUM_THREAD_MUTEX); SUM_THREAD++; pthread_mutex_unlock (&SUM_THREAD_MUTEX); }else{ printf("COLUNA (%lu): Invalida!\n", column); } free(array); pthread_exit((void*) 0); } void *check_block(void *arg){ int *array = init_array(GRID_H+1); int counter, counter2; int sum = 0; long *values = (long*) arg; long line = values[0]; long column = values[1]; printf("BLOCK CHECKER: %lu %lu\n", line, column); for(counter = (int) line; counter < line + BLOCK_OFFSET ; counter++ ){ for(counter2 = (int) column; counter2 < column + BLOCK_OFFSET ; counter2++ ){ pthread_mutex_lock (&GRID_MUTEX[counter][counter2]); unsigned short grid_copy = GRID[counter][counter2]; pthread_mutex_unlock (&GRID_MUTEX[counter][counter2]); if(array[grid_copy] == 0){ sum++; } else { printf("BLOCO (%lu %lu): %hu duplicado em [%d][%d]!\n", line, column, grid_copy, counter, counter2); } array[grid_copy]++; } } if(sum == GRID_H){ printf("BLOCO (%lu %lu): Valido!\n", line, column); pthread_mutex_lock (&SUM_THREAD_MUTEX); SUM_THREAD++; pthread_mutex_unlock (&SUM_THREAD_MUTEX); }else{ printf("BLOCO (%lu %lu): Invalido!\n", line, column); } free(array); pthread_exit((void*) 0); } int main(int argc, char * argv[]){ FILE * file_arg = NULL; /* Opening file */ file_arg = fopen(argv[1], "r+"); /*printf("%s\n", argv[1]);*/ if(file_arg != NULL){ load_grid(file_arg); /*print_grid();*/ } else { perror("Aconteceu um erro"); return -1; } /* Initializing mutex */ init_mutexes(); /* PTHREAD initialization */ pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* Creates all the needed threads */ long counter; long counter2; for(counter = 0; counter < GRID_W; counter++) { pthread_create(&COLUMN_THREAD[counter], &attr, check_column, (void *)counter); } for(counter = 0; counter < GRID_H; counter++) { pthread_create(&LINE_THREAD[counter], &attr, check_line, (void *)counter); } for(counter = 0; counter < GRID_H; counter+=BLOCK_OFFSET){ for(counter2 = 0; counter2 < GRID_W; counter2+=BLOCK_OFFSET){ long * position = (long *) malloc(sizeof(long) * 2); position[0] = counter; position[1] = counter2; pthread_create(&BLOCK_THREAD[counter+counter2], &attr, check_block, (void *)position); } } /* Waits for all threads to finish */ void* status; for(counter = 0; counter < GRID_H; counter++) { pthread_join(LINE_THREAD[counter], &status); pthread_join(COLUMN_THREAD[counter], &status); pthread_join(BLOCK_THREAD[counter], &status); } /* Checking result after all threads modified the SUM_THREAD variable */ if(SUM_THREAD == EXPECTED_SUM){ printf("\n\nMAIN: O sudoku (%s) eh valido!\n", argv[1]); } else { printf("\n\nMAIN: O sudoku (%s) eh invalido!\n", argv[1]); printf("MAIN: Contagem errada -> %d\n", SUM_THREAD); } fclose(file_arg); pthread_attr_destroy(&attr); destroy_mutexes(); pthread_exit(NULL); return 0; }
C
/** * @brief Some mathematical processing functions * @param Mathematical variables to process * @retval Processing the completed mathematical results * @author ZCD * @Time 2020 1 11 */ #include "User_Math.h" #include "math.h" #include "stdlib.h" #include "stm32f4xx_hal.h" /** * @brief Numerical range control.Take the minimum value when it is less than the minimum, take the maximum value when it is greater than the maximum * @param Floating point type * @author ZCD * @Time 2020 1 11 */ float NumRangeLimit(float Num_Input, float Num_Min, float Num_Max) { if(Num_Input<Num_Min) { return Num_Min; } else if(Num_Input>Num_Max) { return Num_Max; } else { return Num_Input; } } /** * @brief Numerical range control.Absolute value * @param Integer type * @author ZCD * @Time 2020 1 11 */ int NumRangeLimit_ABS(int Num_Input,int Num_Min, int Num_Max) { int Num_temp=0; Num_temp = abs(Num_Input); if(Num_temp<Num_Min) { return Num_Min; } else if(Num_temp>Num_Max) { return Num_Max; } else { return Num_temp; } } //仯Ƽ uint8_t Value_Change_Trend_ABS (int16_t Num ,int16_t Num_Last) { Num=abs(Num); Num_Last=abs(Num_Last); if(Num-Num_Last>=5) { return 1; } else { return 2; } } /** * @brief Increasing slope function * @param End value; End value slope; * @author ZCD * @Time 2020 1 15 */ float Ramp_Increase(Ramp_Init_e* Ramp_Temp) { Ramp_Temp->count++; HAL_Delay(Ramp_Temp->TIME_PerCal); Ramp_Temp->Ramp_Buf=(Ramp_Temp->End_Value/Ramp_Temp->count_SUM)*Ramp_Temp->count; Ramp_Temp->Output=Ramp_Temp->Ramp_Buf; return Ramp_Temp->Output; } /** * @brief Decreasing slope function * @param End value; End value slope; * @author ZCD * @Time 2020 1 15 */ float Ramp_Decrease(Ramp_Init_e* Ramp_Temp) { Ramp_Temp->count++; HAL_Delay(Ramp_Temp->TIME_PerCal); Ramp_Temp->Ramp_Buf=Ramp_Temp->End_Value - (Ramp_Temp->End_Value/Ramp_Temp->count_SUM)*Ramp_Temp->count; Ramp_Temp->Output=Ramp_Temp->Ramp_Buf; return Ramp_Temp->Output; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_input.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gvitor-s <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/12 17:21:49 by gvitor-s #+# #+# */ /* Updated: 2021/08/27 18:16:29 by gvitor-s ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" static int check_imaginary(char *b); static int check_real(char *b); void check_input(int argc, char **argv, t_fractol *fractol) { if (!ft_strcmp(argv[1], "mandelbrot")) fractol->flag = mandelbrot; else if (!ft_strcmp(argv[1], "julia")) { if (argc < 4) error_handler(COMPLEX_ARGUMENTS, NULL); fractol->flag = julia; if (check_real(argv[2])) error_handler(REAL_PART, NULL); fractol->c.re = ft_atod(argv[2]); if (!ft_strrchr(argv[3], 'i') || check_imaginary(argv[3])) error_handler(IMAGINARY_PART, NULL); if (*argv[3] == 'i' || (*argv[3] == '-' && *(argv[3] + 1) == 'i')) fractol->c.im = (*argv[3] == 'i') + ((*argv[3] == '-' && *(argv[3] + 1) == 'i') * (-1.0)); else fractol->c.im = ft_atod(argv[3]); } else if (!ft_strcmp(argv[1], "burnship")) fractol->flag = burnship; else error_handler(AVAILABLE_SETS, NULL); } static int check_imaginary(char *part) { if (*part == '-' || *part == '+') part++; else return (ERROR); while (*part && *part != 'i') { if ((!ft_isdigit(*part) && *part != '.') || (*part == '.' && !ft_isdigit(*(part + 1))) || (*part == '.' && !ft_isdigit(*(part - 1)))) return (ERROR); part++; } if (*part == 'i' && *(part + 1) != '\0') return (ERROR); return (OK); } static int check_real(char *part) { if (*part == '-' || *part == '+') part++; while (*part) { if ((!ft_isdigit(*part) && *part != '.') || (*part == '.' && !ft_isdigit(*(part + 1))) || (*part == '.' && !ft_isdigit(*(part - 1)))) return (ERROR); part++; } return (OK); }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int x, y; printf("Digite um numero:"); scanf("%d",&x); if(x<1){ y = x; printf("\nImprimindo y: %d",y); } else if(x == 1){ y = 0; printf("\nImprimindo y: %d",y); } else if(x>1){ y = x*x; printf("\nImprimindo y: %d",y); } return 0; }
C
/* * Copyright 2016 Aaron Barany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <DeepSea/Core/Streams/Path.h> #include <DeepSea/Core/Error.h> #include <string.h> bool dsPath_combine(char* result, size_t resultSize, const char* path1, const char* path2) { if (!result || resultSize == 0 || result == path2) { errno = EINVAL; return false; } size_t len1 = path1 ? strlen(path1) : 0; size_t len2 = path2 ? strlen(path2) : 0; // Handle when one or both paths are empty. if (!len1 && !len2) { *result = 0; return true; } if (len1 && !len2) { if (resultSize < len1 + 1) { errno = ESIZE; return false; } if (result != path1) strncpy(result, path1, len1 + 1); return true; } if (!len1 && len2) { if (resultSize < len2 + 1) { errno = ESIZE; return false; } strncpy(result, path2, len2 + 1); return true; } // Remove the path separator if present for each path. for (; len1 > 0; --len1) { if (path1[len1 - 1] != DS_PATH_SEPARATOR && path1[len1 - 1] != DS_PATH_ALT_SEPARATOR) break; } for (; len2 > 0; ++path2, --len2) { if (path2[0] != DS_PATH_SEPARATOR && path2[0] != DS_PATH_ALT_SEPARATOR) break; } if (resultSize < (len1 + len2 + 2)) { errno = ESIZE; return false; } if (result != path1) strncpy(result, path1, len1); result[len1] = DS_PATH_SEPARATOR; strncpy(result + len1 + 1, path2, len2 + 1); return true; } bool dsPath_isAbsolute(const char* path) { if (!path) return false; size_t length = strlen(path); if (length == 0) return false; if (path[0] == DS_PATH_SEPARATOR || path[0] == DS_PATH_ALT_SEPARATOR) return true; #if DS_WINDOWS if (path[1] == ':') return true; #endif return false; } bool dsPath_getDirectoryName(char* result, size_t resultSize, const char* path) { if (!result || resultSize == 0 || !path) { errno = EINVAL; return false; } // Search for the last path separator. size_t length = strlen(path); if (length == 0) { errno = EINVAL; return false; } size_t end = length - 1; do { if (path[end] == DS_PATH_SEPARATOR || path[end] == DS_PATH_ALT_SEPARATOR) { // Get rid of any extra path separators. for (; end > 0 && (path[end - 1] == DS_PATH_SEPARATOR || path[end - 1] == DS_PATH_ALT_SEPARATOR); --end) { } // Keep separator if at the root. if (end == 0) { if (resultSize < 2) { errno = ESIZE; return false; } result[0] = DS_PATH_SEPARATOR; result[1] = 0; return true; } else { if (resultSize < end + 1) { errno = ESIZE; return false; } if (result != path) strncpy(result, path, end); result[end] = 0; return true; } } if (end-- == 0) { errno = EINVAL; return false; } } while (true); } const char* dsPath_getFileName(const char* path) { if (!path) return NULL; // Search for the last path separator. size_t end = strlen(path) - 1; do { if (path[end] == DS_PATH_SEPARATOR || path[end] == DS_PATH_ALT_SEPARATOR) return path + end + 1; if (end-- == 0) return path; } while (true); } const char* dsPath_getExtension(const char* path) { const char* fileName = dsPath_getFileName(path); if (!fileName) return NULL; // Search for the first '.' in the file name. for (size_t i = 0; fileName[i]; ++i) { if (fileName[i] == '.') return fileName + i; } return NULL; } const char* dsPath_getLastExtension(const char* path) { const char* fileName = dsPath_getFileName(path); if (!fileName) return NULL; // Search for the last '.'. size_t end = strlen(fileName) - 1; do { if (fileName[end] == '.') return fileName + end; if (end-- == 0) return NULL; } while (true); } bool dsPath_removeLastExtension(char* result, size_t resultSize, const char* path) { if (!result || resultSize == 0 || !path) { errno = EINVAL; return false; } const char* extension = dsPath_getLastExtension(path); size_t len; if (extension) len = extension - path; else len = strlen(path); if (resultSize < len + 1) { errno = ESIZE; return false; } if (result != path) strncpy(result, path, len); result[len] = 0; return true; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> double factorial(int n); double e_a_la_x(int x, int tol); int main() { int num, tol; printf("Ingrese un numero y una tolerancia: \n"); scanf("%d",&num); scanf("%d",&tol); printf("\nEl numero calculado es %lf", e_a_la_x(num,tol)); return 0; } double factorial(int n) { int r=1,cont=1; while(cont <=n){ r*=cont; cont++; } return r; } double e_a_la_x(int x, int tol) { double rtdo=0; int i=0; while(rtdo < tol){ rtdo+= pow(x,i)/ factorial(i); i++; } return rtdo; }
C
#include <stdio.h> #include <stdlib.h> int main() { int sayi,a,b,c,d,e,f; printf("4 basamakli bir sayi giriniz : "); scanf("%d",&sayi); a=sayi%10; b=(sayi%100)-a; c=((sayi%100)-a)/10; d=(sayi%1000)-(a+b); e=((sayi%1000)-(a+b))/100; f=(sayi-(a+b+d))/1000; if(((f*10)+e)*((c*10)+a)==((e*10)+f)*((a*10)+c)) printf("Girdiginiz sayi tersyuz bir sayidir."); else printf("Girdiginiz sayi tersyuz bir sayi degildir."); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <math.h> #include <stdbool.h> #include <string.h> MPI_Status status; size_t n, m; size_t TIME; int process_rank, process_number; const double K = 401.0 / (8960.0 * 380.0); double H; double TAU; struct Cell { size_t width; size_t height; int number; double** temperature; }; typedef struct Cell Cell; size_t get_cell_height(size_t cell_number) { size_t cells_height = n / (process_number - 1); return ((cell_number + 1) * cells_height <= n) ? cells_height : (n - cell_number * cells_height); } size_t get_index(size_t start, size_t time, size_t process, size_t step) { return start + (time * process_number + process) * 4 + step; } void init_cell(Cell* cell, size_t width, size_t height, int cell_number) { cell->temperature = (double**)malloc(sizeof(double*) * height); for (size_t i = 0; i < height; ++i) { cell->temperature[i] = (double*)malloc(sizeof(double) * (m + 2)); } cell->width = width; cell->height = height; cell->number = cell_number; } void free_cell(Cell* cell) { for (size_t i = 0; i < cell->height; ++i) { free(cell->temperature[i]); } free(cell->temperature); } void fill(Cell* cell, double value) { for (size_t i = 0; i < cell->height; ++i) { for (size_t j = 0; j < cell->width; ++j) { cell->temperature[i][j] = value; } } } void process_cell(Cell* cell) { // Calculating temporary matrix double** tmp = (double**)malloc(sizeof(double*) * cell->height); for (int i = 0; i < cell->height; ++i) { tmp[i] = (double*)malloc(sizeof(double) * cell->width); tmp[i][0] = cell->temperature[i][0]; tmp[i][cell->width - 1] = cell->temperature[i][cell->width - 1]; } for (int j = 0; j < cell->width; ++j) { tmp[0][j] = cell->temperature[cell->height - 1][j]; tmp[cell->height - 1][j] = cell->temperature[cell->height - 1][j]; } for (int i = 1; i < cell->height - 1; ++i) { for (int j = 1; j < cell->width - 1; ++j) { tmp[i][j] = cell->temperature[i][j] + K * TAU / (H * H) * (cell->temperature[i + 1][j] - 2 * cell->temperature[i][j] + cell->temperature[i - 1][j]); } } // Calculating temperature matrix for(size_t i = 1; i < cell->height - 1; ++i) { for (size_t j = 1; j < cell->width - 1; ++j) { cell->temperature[i][j] = tmp[i][j] + K * TAU / (H * H) * (tmp[i][j + 1] - 2 * tmp[i][j] + tmp[i][j - 1]); } } // free memory for (int i = 0; i < cell->height; ++i) { free(tmp[i]); } free(tmp); } void send_string(Cell* cell, size_t string_number, size_t receiveing_process, int index) { MPI_Send(&cell->temperature[string_number][0], m + 2, MPI_DOUBLE, receiveing_process, index, MPI_COMM_WORLD); } void receive_string(Cell* cell, size_t string_number, size_t sending_process, int index) { if (process_rank == cell->number) { MPI_Recv(&cell->temperature[string_number][0], m + 2, MPI_DOUBLE, sending_process, index, MPI_COMM_WORLD, &status); } } void send_up(Cell* cell, int index) { if (process_rank != 0) { send_string(cell, 1, process_rank - 1, index); } } void send_down(Cell* cell, int index) { size_t last_process; if (n % (process_number - 1) == 0) { last_process = process_number - 2; } else { last_process = process_number - 1; } if (process_rank != last_process) { send_string(cell, cell->height - 2, process_rank + 1, index); } } void receive_up(Cell* cell, int index) { if (process_rank != 0) { receive_string(cell, 0, process_rank - 1, index); } /* else { for (int i = 0; i < cell->width; ++i) { cell->temperature[0][i] = cell->temperature[1][i]; } } */ } void receive_down(Cell* cell, int index) { size_t last_process; if (n % (process_number - 1) == 0) { last_process = process_number - 2; } else { last_process = process_number - 1; } if (process_rank != last_process) { receive_string(cell, cell->height - 1, process_rank + 1, index); } /* else { for (int i = 0; i < cell->width; ++i) { cell->temperature[cell->height - 1][i] = cell->temperature[cell->height - 2][i]; } } */ } void send_cell(Cell* cell, size_t receiveing_proces, int index) { for (int i = 0; i < cell->height; ++i) { send_string(cell, i, receiveing_proces, index + i); } } void receive_cell(Cell* cell, size_t sending_proces, int index) { init_cell(cell, m + 2, get_cell_height(process_rank) + 2, process_rank); for (int i = 0; i < cell->height; ++i) { receive_string(cell, i, sending_proces, index + i); } } void print_cell(Cell* cell) { for (size_t i = 1; i < cell->height - 1; ++i) { for (size_t j = 1; j < cell->width - 1; ++j) { printf("%lf ", cell->temperature[i][j]); } printf("\n"); } } int main(int argc, char** argv) { MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &process_number); MPI_Comm_rank(MPI_COMM_WORLD, &process_rank); // Check that there are enough arguments if (argc < 7) { printf("Not enough arguments!\n"); MPI_Finalize(); return 0; } double begin_time, end_time; H = atof(argv[5]); int seconds = atoi(argv[6]); TAU = H * H / (2 * K); TIME = seconds / TAU + ((seconds / TAU - (int)(seconds / TAU) < 0.5) ? 0 : 1); // Getting matrix size from command line n = (size_t)(atof(argv[3]) / H); // strings m = (size_t)(atof(argv[4]) / H); // columns if (process_number == 1) { printf("Need at least 2 processes!\n"); MPI_Finalize(); return 0; } size_t cells_height = n / (process_number - 1); size_t cells_number = process_number - 1; if (n % (process_number - 1) != 0) { ++cells_number; } // Base process if (process_rank == process_number - 1) { for (size_t i = 0; i < cells_number; ++i) { Cell* new_cell = (Cell*)malloc(sizeof(Cell)); init_cell(new_cell, m + 2, get_cell_height(i) + 2, i); // initial conditions fill(new_cell, 5); for (size_t j = 0; j < get_cell_height(i) + 2; ++j) { new_cell->temperature[j][0] = 80.0; new_cell->temperature[j][m + 1] = 30.0; } if (i == 0) { for (size_t j = 0; j < m + 2; ++j) { new_cell->temperature[0][j] = 100; } } if (i == cells_number - 1) { for (size_t j = 0; j < m + 2; ++j) { new_cell->temperature[get_cell_height(i) + 1][j] = 0; } } // The last cell may be for base process if ((n % (process_number - 1) == 0) || (i != cells_number)) { send_cell(new_cell, i, i * n); } free_cell(new_cell); free(new_cell); } } Cell cell; // Working processes if ((process_rank != process_number - 1) || (n % (process_number - 1) != 0)) { receive_cell(&cell, process_number - 1, process_rank * n); } const char* algorithm = argv[2]; MPI_Barrier(MPI_COMM_WORLD); if (process_rank == process_number - 1) { begin_time = MPI_Wtime(); } if (strcmp(algorithm, "slow") == 0) { if ((process_rank != process_number - 1) || (n % (process_number - 1) != 0)) { size_t last_process = (n % (process_number - 1) == 0) ? process_number - 2 : process_number - 1; if (cells_number > 2) { for (size_t time = 0; time < TIME; ++time) { for (size_t process = 0; process <= last_process - 1; ++process) { if (process_rank == process) { send_down(&cell, 0); } if (process_rank == process + 1) { receive_up(&cell, 0); } } for (size_t process = last_process; process >= 1; --process) { if (process_rank == process) { send_up(&cell, 0); } if (process_rank == process - 1) { receive_down(&cell, 0); } } process_cell(&cell); } } else if (cells_number == 2) { for (size_t time = 0; time < TIME; ++time) { if (process_rank == 0) { send_down(&cell, get_index(n * cells_number, time, process_rank, 0)); } else { receive_up(&cell, get_index(n * cells_number, time, process_rank - 1, 0)); } if (process_rank == 0) { receive_down(&cell, get_index(n * cells_number, time, process_rank, 1)); } else { send_up(&cell, get_index(n * cells_number, time, process_rank - 1, 1)); } process_cell(&cell); } } else { for (size_t time = 0; time < TIME; ++time) { process_cell(&cell); } } } } else { if ((process_rank != process_number - 1) || (n % (process_number - 1) != 0)) { for (size_t time = 0; time < TIME; ++time) { if (process_rank % 2 == 0) { send_down(&cell, get_index(n * cells_number, time, process_rank, 0)); } else { receive_up(&cell, get_index(n * cells_number, time, process_rank - 1, 0)); } if (process_rank % 2 == 0) { receive_down(&cell, get_index(n * cells_number, time, process_rank + 1, 1)); } else { send_up(&cell, get_index(n * cells_number, time, process_rank, 1)); } if (process_rank % 2 == 0) { receive_up(&cell, get_index(n * cells_number, time, process_rank - 1, 2)); } else { send_down(&cell, get_index(n * cells_number, time, process_rank, 2)); } if (process_rank % 2 == 0) { send_up(&cell, get_index(n * cells_number, time, process_rank, 3)); } else { receive_down(&cell, get_index(n * cells_number, time, process_rank + 1, 3)); } process_cell(&cell); } } } const char* mode = argv[1]; MPI_Barrier(MPI_COMM_WORLD); if (process_rank == process_number - 1) { end_time = MPI_Wtime(); if (strcmp(mode, "time") == 0) { printf("%lf ", end_time - begin_time); } } if (strcmp(mode, "temperature") == 0) { if (process_rank == process_number - 1) { printf("%lf %d %d\n", H, n, m); } MPI_Barrier(MPI_COMM_WORLD); for (size_t i = 0; i < cells_number; ++i) { MPI_Barrier(MPI_COMM_WORLD); if (process_rank == i) { print_cell(&cell); } MPI_Barrier(MPI_COMM_WORLD); } } //free_cell(&cell); MPI_Finalize(); return 0; }
C
#include<stdio.h> int main() { int i; float marks[5]={}; printf("Enter name of student\n"); for(i=0;i<5;i++) { scanf("%f",&marks[i]); } for(i=0;i<10;i++) { printf("%.2f",marks[i]); } }
C
#include<stdio.h> int main(void){ int sa = 5050,sb = 0; for(int i = 1;i<=100;i++){ sb += i*i; printf("%d\n",sb); } printf("%d\n",sb); sa = sa*sa; printf("%d\n",sa-sb ); return 0; }
C
/* Author: Nishan Ghimire Roll no : 210316(BE/D) Question Print all armstrong number */ # include<stdio.h> # include<math.h> int main(){ int sum,num,n,terms,rem; terms = 999; for (int i = 100; i < terms; i++) { sum = 0; n = i; while (n > 0) { rem = n%10; sum+=pow(rem,3); n /= 10; } if(sum == i){ printf("%d\t",sum); } } return 0; }
C
/*----------------------------------------------------------------------------- ** Copyright (C) 2001 Radical Entertainment Ltd. All rights reserved. ** ** winutil.h ** ** Description: A set of utilities which are specific to the windows development ** environment. ** ** Modification History: ** + Created Aug 03, 2001 -- bkusy **---------------------------------------------------------------------------*/ /*---------------------------------------- ** System Includes **--------------------------------------*/ #include <string.h> #include <stdio.h> #include <assert.h> /*---------------------------------------- ** Project Includes **--------------------------------------*/ #include "util.h" /*---------------------------------------- ** Constants **--------------------------------------*/ #define BUFFER_SIZE 512 /*---------------------------------------- ** Globals **--------------------------------------*/ char* util_optarg; int util_optind; int util_opterr = 1; int util_optopt; /*----------------------------------------------------------------------------- ** u t i l _ b a s e n a m e ** ** Synopsis: Determine the basename in a file path. ( eg/ would return ** "newfile.c" from the path "/usr/home/newfile.c". ** ** Parameters: buffer - buffer to receive basename. ** size - size of buffer. ** path - path to determine basename from. ** ** Returns: non-zero if successful, 0 if buffer is too small. ** ** Constraints: path must use '/' and not '\' as directory separators. ** **---------------------------------------------------------------------------*/ int util_basename( char* buffer, int size, const char* path ) { char* d; char* n; char* e; int length; int result = 0; assert( buffer ); util_decomposeFilePath( path, &d, &n, &e ); length = strlen( n ) + strlen( e ) + 1; if ( length < size ) { strcpy( buffer, n ); strcat( buffer, "." ); strcat( buffer, e ); result = 1; } return result; } /*----------------------------------------------------------------------------- ** u t i l _ c h a n g e F i l e E x t e n s i o n ** ** Synopsis: Changes the file extension in the given buffer to the given ** given extension. ** ** Parameters: buffer - the file path to be modified. ** ext - the new file extension. ** ** Returns: NOTHING ** ** Constraints: If the original file path does not have an extension, as ** identified by the presence of a "." character, no change will ** take place. ** If the new extension is longer than the old extension, no ** change will take place. ** **---------------------------------------------------------------------------*/ void util_changeFileExtension( char* buffer, const char* ext ) { char* oldExt = 0; assert( buffer ); assert( ext ); oldExt = (char*)(util_rindex( buffer, '.' )); if ( oldExt ) { oldExt++; if ( strlen( oldExt ) <= strlen( ext ) ) { strcpy( oldExt, ext ); } } } /*----------------------------------------------------------------------------- ** u t i l _ d e c o m p o s e F i l e P a t h ** ** Synopsis: Decompose a file path into its directory, filename and extension. ** ** Parameters: path - the path to decompose. ** dir - a pointer which will be set to the start of the directory. ** name - a pointer which will be set to the start of the name. ** ext - a pointer which will be set to the start of the extension. ** ** Returns: NOTHING ** ** Constraints: path must use '/' and not '\' as directory separators. The pointers ** returned in dir, name, and ext are only valid until the next call ** to util_DecomposePath(). ** **---------------------------------------------------------------------------*/ void util_decomposeFilePath( const char* path, char** dir, char** name, char** ext ) { static char buffer[ BUFFER_SIZE + 1 ]; strncpy( buffer, path, BUFFER_SIZE ); *ext = strrchr( buffer, '.' ); if ( *ext ) { /* * Remove the extension by replacing '.' with a NULL character. */ **ext = '\0'; /* * The extension will be in the next position. */ (*ext)++; } *name = strrchr( buffer, '/' ); if ( *name ) { /* * Remove the name by replacing the last '/' with a NULL character. */ **name = '\0'; /* * The name will be in the next position. */ (*name)++; /* * Set dir to the start of the string and we are done. */ *dir = buffer; } else { /* * Name must extend to the beginning of the path. Set the name pointer * accordingly and set dir to null. */ *name = buffer; *dir = 0; } } /*----------------------------------------------------------------------------- ** u t i l _ d i r n a m e ** ** Synopsis: Determine the directory in a file path. ** ** Parameters: buffer - buffer to recieve directory. ** size - size of buffer. ** path - the path to retrieve the directory from. ** ** Returns: non-zero if successful, zero if buffer is too small to receive ** the directory. ** ** Constraints: path must use '/' and not '\' as directory separators. ** **---------------------------------------------------------------------------*/ int util_dirname( char* buffer, int size, const char* path ) { char* d; char* n; char* e; int length; int result = 0; util_decomposeFilePath( path, &d, &n, &e ); length = strlen( d ); if ( length < size ) { strcpy( buffer, d ); result = 1; } return result; } /*----------------------------------------------------------------------------- ** u t i l _ f i l e E x i s t s ** ** Synopsis: Determines if the give file exists. ** ** Parameters: filename - the name of the file to check for existence. ** ** Returns: 0 if file does not exist, non-zero otherwise. ** ** Constraints: ** **---------------------------------------------------------------------------*/ int util_fileExists( const char* filename ) { FILE *fp; assert( filename ); fp = fopen( filename, "r" ); if ( fp ) { fclose( fp ); return 1; } return 0; } /*----------------------------------------------------------------------------- ** u t i l _ g e t o p t _ i n i t ** ** Synopsis: Initializes the getopt parser. ** ** Parameters: NONE ** ** Returns: NOTHING ** ** Constraints: NONE ** ** Author: Angus Mackay ** **---------------------------------------------------------------------------*/ void util_getopt_init() { util_optind = 1; } /*----------------------------------------------------------------------------- ** u t i l _ g e t o p t ** ** Synopsis: Used to parse command line arguments based on a specified ** syntax. The argument for the current option is stored in ** the global variable "util_optarg". ** ** Parameters: argc - the number of arguments in the array. ** argv - the argumnet array. ** opts - option specifier string. Options can be of two forms: ** boolean flags ( its either there or it isn't ) and ** flag value pairs in which a flag is always followed ** by some value. Options which require an argument ** must be followed by a ":" in the option specifier ** string. So for a command which can have two boolean ** flags, "h" and "i", and two argument flags, "t" and ** "u", the following option specifier string would be ** used: "hit:u:". ** ** Returns: the option character found, or -1 if no more option ** characters. ** ** Constraints: NONE ** ** Author: Angus Mackay ** **---------------------------------------------------------------------------*/ int util_getopt( int argc, char* const* argv, const char* opts ) { static int init_done = 0; static int suboptionpos = 1; if(!init_done) { util_getopt_init(); init_done = 1; } util_optarg = NULL; if(util_optind == argc) { /* we are done */ return(-1); } if(argv[util_optind][0] == '-') { char *argp; /* test for end of arg marker */ if(argv[util_optind][1] == '-' && argv[util_optind][2] == '\0') { suboptionpos = 1; util_optind++; return(-1); } for(argp=&(argv[util_optind][suboptionpos]); *argp != '\0'; argp++) { char *optp; int numcolon = 0; char *p; if((optp=strchr(opts, *argp)) == NULL) { if(util_opterr != 0) { fprintf(stderr, "%s: illegal option -- %c\n", argv[0], *argp); } util_optopt = *argp; suboptionpos++; if(argv[util_optind][suboptionpos] == '\0') { suboptionpos = 1; util_optind++; } return('?'); } /* zero, one or two colons? */ for(p=(optp+1); *p == ':'; p++) { numcolon++; } switch(numcolon) { /* no argument */ case 0: suboptionpos++; if(argv[util_optind][suboptionpos] == '\0') { suboptionpos = 1; util_optind++; } return(*optp); break; /* manditory argument */ case 1: /* the argument is seperated by a space */ if(argp[1] == '\0') { /* ther are more args */ if(util_optind+1 == argc) { suboptionpos++; if(argv[util_optind][suboptionpos] == '\0') { suboptionpos = 1; util_optind++; } if(util_opterr != 0) { fprintf(stderr, "%s: option requires an argument -- %c\n", argv[0], *argp); } util_optopt = *argp; return('?'); } util_optind++; suboptionpos = 1; util_optarg = argv[util_optind]; util_optind++; return(*optp); } /* the argument is attached */ util_optarg = argp+1; suboptionpos = 1; util_optind++; return(*optp); break; /* optional argument */ case 2: /* the argument is seperated by a space */ if(argp[1] == '\0') { util_optind++; suboptionpos = 1; util_optarg = NULL; return(*optp); } /* the argument is attached */ suboptionpos = 1; util_optarg = argp+1; util_optind++; return(*optp); break; /* a case of too many colons */ default: suboptionpos++; if(argv[util_optind][suboptionpos] == '\0') { suboptionpos = 1; util_optind++; } util_optopt = '?'; return('?'); break; } } suboptionpos = 1; } else { /* we are done */ return(-1); } /* we shouldn't get here */ return(-1); } /*----------------------------------------------------------------------------- ** u t i l _ i n d e x ** ** Synopsis: returns a pointer to the first occurrence of the character ** "c" in the string "s". ** ** Parameters: s - the string to search. ** c - the character to search for. ** ** Returns: a pointer to the matched character, or NULL if the character ** is not found. ** ** Constraints: NONE ** **---------------------------------------------------------------------------*/ const char* util_index( const char* s, int c ) { const char* result = 0; const char* sp = 0; assert( s ); sp = s; while ( *sp != '\0' ) { if ( *sp == c ) { result = sp; break; } sp++; } return result; } /*----------------------------------------------------------------------------- ** u t i l _ p o s i x F i l e P a t h ** ** Synopsis: Ensures the given path uses POSIX style slashes. ** ** Parameters: path - the path to "posixfy". ** ** Returns: NOTHING ** ** Constraints: NONE ** **---------------------------------------------------------------------------*/ void util_posixFilePath( char* path ) { char* pp = path; while ( *pp ) { if ( '\\' == *pp ) *pp = '/'; pp++; } } /*----------------------------------------------------------------------------- ** u t i l _ r e p l a c e C h a r a c t e r s ** ** Synopsis: Replace characters in a string. ** ** Parameters: find - the character to find. ** replace - the charcter to replace the found character with. ** string - the string within which to do the find/replace. ** ** Returns: NOTHING ** ** Constraints: NONE ** **---------------------------------------------------------------------------*/ void util_replaceCharacters( char find, char replace, char* string ) { char* p = 0; if ( string ) { while ( p = strchr( string, find ) ) { *p = replace; } } } /*----------------------------------------------------------------------------- ** u t i l _ r e v e r s e S p a n ** ** Synopsis: Finds the suffix which is composed completely of characters in ** in the spanSet in the specified string. ** ** Example: end = util_ReverseSpan( "name123", "312" ); ** * ** * end now points to "123". ** * ** end = util_ReverseSpan( "name123", "21" ); ** * ** * end would point to NULL because the character "3" is not ** * in the spanSet. ** ** Parameters: string - the string to be searched. ** spanSet - a string of characters that can be in the suffix. ** ** Returns: a pointer to the suffix string, or NULL if there is no ** suffix. ** ** Constraints: NONE ** **---------------------------------------------------------------------------*/ const char* util_reverseSpan( const char* string, const char* spanSet ) { const char* sp = 0; const char* next_sp = 0; int isEndSpan = 0; /* * Set a pointer to the end of the string to be searched. */ sp = string + strlen( string ); /* * If the string passed in is empty, we are done. */ if ( sp == string ) return sp; while( sp > string && !isEndSpan ) { next_sp = sp - 1; if ( strchr( spanSet, *next_sp ) ) { sp--; } else { isEndSpan = 1; } } return sp; } /*----------------------------------------------------------------------------- ** u t i l _ r i n d e x ** ** Synopsis: returns a pointer to the last occurrence of the character ** "c" in the string "s". ** ** Parameters: s - the string to search. ** c - the character to search for. ** ** Returns: a pointer to the matched character, or NULL if the character ** is not found. ** ** Constraints: NONE ** **---------------------------------------------------------------------------*/ const char* util_rindex( const char* s, int c ) { const char* result = 0; const char* sp = 0; int length; assert( s ); length = strlen(s); sp = s + length; if ( length > 0 ) { while ( sp != s ) { sp--; if ( *sp == c ) { result = sp; break; } } } return result; } /*----------------------------------------------------------------------------- ** u t i l _ s u b s t i t u t e ** ** Synopsis: Substitue strings matchin "find" with "replace" in "string". ** If this cannot be done without exceeding the size of "string" ** An error will be returned and "string" will be as it was ** when util_substitute was originally called. ** ** Parameters: find - the substring to find. ** replace - the substring to insert in place of found strings. ** string - the string to operate on. ** stringSize - the maximum size the string can grow to. ** firstOnly - flag. If non-zero only the first occurence of ** "find" will be replaced. If zero, all occurences ** will be replaced. ** ** Returns: 0 on error, the new size of the string on success. ** ** Constraints: NONE ** **---------------------------------------------------------------------------*/ int util_substitute( const char* find, const char* replace, char* string, int stringSize, int firstOnly ) { char buffer[ BUFFER_SIZE + 1 ]; char* sp; char* bp; char* p; int findLength = strlen( find ); int replaceLength = strlen( replace ); int count = 0; int total = 0; int tooBig = 0; int status = 0; assert( stringSize <= BUFFER_SIZE ); bp = buffer; sp = string; while( !tooBig && (p = strstr( sp, find )) ) { /* * Determine the number of characters since last find. * Add to total characters. * If total characters exceeds "stringSize" then break and return * error. Otherwise copy characters since last find to buffer. */ count = p - sp; total += count; if ( total >= stringSize ) { tooBig = 1; continue; } strncpy( bp, sp, count ); bp += count; *bp = '\0'; /* * If adding the replace string causes buffer to exceed "stringSize" * break and return error. Otherwise copy the replace string into * buffer. */ total += replaceLength; if ( total >= stringSize ) { tooBig = 1; continue; } strcpy( bp, replace ); bp += replaceLength; /* * Update the position of sp so that it points to next character * after the last found "find" string. */ sp += count + findLength; } if ( !tooBig ) { /* * Attempt to copy the remaining portion of string into buffer. * If successful, copy buffer into string and return success. * Otherwise return error. */ total += strlen( sp ); if ( total < stringSize ) { strcpy( bp, sp ); strcpy( string, buffer ); status = strlen( string ); } } return status; }
C
#pragma once #ifndef BASE64_H #define BASE64_H size_t base64_encode_s(unsigned char *out, const unsigned char *src, size_t len, size_t line_max); /** * base64_encode - Base64 encode * @src: Data to be encoded * @len: Length of the data to be encoded * @out_len: Pointer to output length variable, or %NULL if not used * Returns: Allocated buffer of out_len bytes of encoded data, * or %NULL on failure * * Caller is responsible for freeing the returned buffer. Returned buffer is * nul terminated to make it easier to use as a C string. The nul terminator is * not included in out_len. */ unsigned char * base64_encode(const unsigned char *src, size_t len, size_t *out_len); /** * Base64 decode. * Caller is responsible for freeing the returned buffer. * @param src Data to be decoded * @param len Length of the data to be decoded * @param out_len Pointer to output length variable * @returns Allocated buffer of out_len bytes of decoded data, or %NULL on failure */ unsigned char * base64_decode(const unsigned char *src, size_t len, size_t *out_len); /** * Calculate the required buffer size of a string of n characters. * @param line_max is the max line length. 0 = no limit; 72 = typical. */ static size_t base64_out_len(size_t n, size_t line_max) { /* RFE Techincally this should be ok but with shorted padding */ #if 0 return ((4 * n / 3) + 3) & ~3; #endif size_t olen; olen = n * 4 / 3 + 4; /* 3-byte blocks to 4-byte */ olen += olen / line_max; /* line feeds */ return olen; } #endif /* BASE64_H */
C
#include <stdio.h> int main() { int rollno[50],marks[50],i,n; printf("\nEnter number of students: "); scanf("%d", &n); for(i=0;i<n;i++) { printf("Enter Roll of Student [%d] : ",i+1); scanf("%d",&rollno[i]); printf("Enter Mark of Student [%d]: ",i+1); scanf("%d",&marks[i]); } printf("\nfollowing is the data entered by the user :- \n"); for(i=0;i<n;i++) { printf("\nRoll No : %d , Marks : %d ",rollno[i],marks[i]); } return 0; }
C
/* BP: Entrenamiento de redes neuronales feedforward de 3 capas (entrada - oculta - salida). Algoritmo: Backpropagation estocastico. Capa intermedia con unidades sigmoideas. Salidas con unidades lineales. PMG - Ultima revision: 18/02/2002 */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <unistd.h> /* parametros de la red y el entrenamiento */ static int N1; /* N1: NEURONAS EN CAPA DE ENTRADA */ static int N2; /* N2: NEURONAS EN CAPA INTERMEDIA */ static int N3; /* N2: NEURONAS EN CAPA DE SALIDA */ static int ITER; /* Total de Iteraciones */ static float ETA; /* learning rate */ static float u; /* Momentum */ static int NERROR; /* graba error cada NERROR iteraciones */ static int WTS; /* numero de archivo de sinapsis inicial WTS=0 implica empezar la red con valores de sinapsis al azar */ static int PTOT; /* cantidad TOTAL de patrones en el archivo .data */ static int PR; /* cantidad de patrones de ENTRENAMIENTO */ static int PTEST; /* cantidad de patrones de TEST (archivo .test) */ /* cantidad de patrones de VALIDACION: PTOT - PR */ static int SEED; /* semilla para la funcion rand(). Los posibles valores son: */ /* SEED: -1: No mezclar los patrones: usar los primeros PR para entrenar y el resto para validar.Toma la semilla del rand con el reloj. 0: Seleccionar semilla con el reloj, y mezclar los patrones. >0: Usa el numero leido como semilla, y mezcla los patrones. */ static int CONTROL; /* nivel de verbosity: 0 -> solo resumen, 1 -> 0 + pesos, 2 -> 1 + datos */ static float GAMMA = 0; /* término de penalización */ static float discrete_error; /* matrices globales */ static float **data; /* train data */ static float **test; /* test data */ static float **w1, **w2; /* pesos entre neuronas */ static float *grad2, *grad3; /* gradiente en cada unidad */ static float **dw1, **dw2; /* correccion a cada peso */ static float *x1, *x2, *x3; /* activaciones de cada capa */ static float **pred; /* salidas predichas */ static float *target; /* valor correcto de la salida */ static int *seq; /* sequencia de presentacion de los patrones */ /* variables globales auxiliares */ static char filepat[100]; static char *nameprefix; /* bandera de error */ static int error; /* funcion sigmoidea */ static float sigmoid(float h) { return 1.0f/(1.0f+expf(-h)); } /* ------------------------------------------------------------------------------- */ /*sinapsis_rnd: Inicializa al azar los valores de todas las sinapsis Los valores se toman entre [-max , max] SEED contiene la semilla del rand(). Si SEED es <=0 se toma como semilla el reloj*/ /* ------------------------------------------------------------------------------- */ static void sinapsis_rnd(float max) { int i, j; float x; /* Semilla para la funcion rand() */ if (SEED < 0) srand((unsigned)time(NULL)); else { if (SEED == 0) { SEED = time(NULL); SEED |= clock() << 16; SEED ^= getpid() << 8; } srand((unsigned)SEED); } /* primer capa */ for (j = 1; j <= N2; j++) for (i = 0; i <= N1; i++) { x = (float)rand(); x /= (RAND_MAX / 2); x -= 1.0; x *= max; w1[j][i] = x; } /* segunda capa */ for (j = 1; j <= N3; j++) for (i = 0; i <= N2; i++) { x = (float)rand(); x /= (RAND_MAX / 2); x -= 1.0; x *= max; w2[j][i] = x; } } /* ------------------------------------------------------------------- */ /*sinapsis_save: guarda valores de las sinapsis en un archivo. El nombre del archivo de salida es (WTS).wts, donde WTS es un entero.*/ /* ------------------------------------------------------------------- */ static int sinapsis_save(int WTS) { int i, j; FILE *fp; int largo; char p[130]; snprintf(p, sizeof(p), "%s-%d.wts", nameprefix, WTS); if ((fp = fopen(p, "w")) == NULL) return 1; /*primer capa */ for (j = 1; j <= N2; j++) for (i = 0; i <= N1; i++) fprintf(fp, "%f\n", w1[j][i]); /*segunda capa */ for (i = 1; i <= N3; i++) for (j = 0; j <= N2; j++) fprintf(fp, "%f\n", w2[i][j]); fclose(fp); return 0; } /* --------------------------------------------------------------------- */ /*sinapsis_read: lee valores de las sinapsis desde un archivo. El nombre del archivo de entrada es (WTS).wts , donde WTS es un entero.*/ /* --------------------------------------------------------------------- */ static int sinapsis_read(int WTS) { int i, j; FILE *fp; int largo; char p[130]; snprintf(p, sizeof(p), "%s-%d.wts", nameprefix, WTS); if ((fp = fopen(p, "r")) == NULL) return 1; /*primera capa */ for (j = 1; j <= N2; j++) for (i = 0; i <= N1; i++) fscanf(fp, "%f", &w1[j][i]); /*segunda capa */ for (i = 1; i <= N3; i++) for (j = 0; j <= N2; j++) fscanf(fp, "%f", &w2[i][j]); fclose(fp); return 0; } /* -------------------------------------------------------------------------- */ /*define_matrix: reserva espacio en memoria para todas las matrices declaradas. Todas las dimensiones son leidas del archivo .net en la funcion arquitec() */ /* -------------------------------------------------------------------------- */ static int define_matrix() { int i; int max; if (PTOT > PTEST) max = PTOT; else max = PTEST; seq = (int *)calloc(max, sizeof(int)); x1 = (float *)calloc(N1 + 1, sizeof(float)); x2 = (float *)calloc(N2 + 1, sizeof(float)); x3 = (float *)calloc(N3 + 1, sizeof(float)); grad2 = (float *)calloc(N2 + 1, sizeof(float)); grad3 = (float *)calloc(N3 + 1, sizeof(float)); target = (float *)calloc(N3 + 1, sizeof(float)); if (seq == NULL || x1 == NULL || x2 == NULL || x3 == NULL || grad2 == NULL || grad3 == NULL || target == NULL) return 1; w1 = (float **)calloc(N2 + 1, sizeof(float *)); w2 = (float **)calloc(N3 + 1, sizeof(float *)); dw1 = (float **)calloc(N2 + 1, sizeof(float *)); dw2 = (float **)calloc(N3 + 1, sizeof(float *)); data = (float **)calloc(PTOT, sizeof(float *)); if (PTEST) test = (float **)calloc(PTEST, sizeof(float *)); pred = (float **)calloc(max, sizeof(float *)); if (w1 == NULL || w2 == NULL || dw1 == NULL || dw2 == NULL || data == NULL || (PTEST && test == NULL) || pred == NULL) return 1; for (i = 0; i <= N2; i++) { w1[i] = (float *)calloc(N1 + 1, sizeof(float)); dw1[i] = (float *)calloc(N1 + 1, sizeof(float)); if (w1[i] == NULL || dw1[i] == NULL) return 1; } for (i = 0; i <= N3; i++) { w2[i] = (float *)calloc(N2 + 1, sizeof(float)); dw2[i] = (float *)calloc(N2 + 1, sizeof(float)); if (w2[i] == NULL || dw2[i] == NULL) return 1; } for (i = 0; i < PTOT; i++) { data[i] = (float *)calloc(N1 + N3 + 1, sizeof(float)); if (data[i] == NULL) return 1; } for (i = 0; i < PTEST; i++) { test[i] = (float *)calloc(N1 + N3 + 1, sizeof(float)); if (test[i] == NULL) return 1; } for (i = 0; i < max; i++) { pred[i] = (float *)calloc(N3 + 1, sizeof(float)); if (pred[i] == NULL) return 1; } return 0; } /* ---------------------------------------------------------------------------------- */ /*arquitec: Lee el archivo .net e inicializa la red en funcion de los valores leidos filename es el nombre del archivo .net (sin la extension) */ /* ---------------------------------------------------------------------------------- */ static int arquitec(char *filename) { int i, j; FILE *b; /* Paso 1: leer el archivo con la configuracion */ sprintf(filepat, "%s.net", filename); b = fopen(filepat, "r"); error = (b == NULL); if (error) { printf("Error al abrir el archivo de parametros\n"); return 1; } /* Estructura de la red */ fscanf(b, "%d", &N1); fscanf(b, "%d", &N2); fscanf(b, "%d", &N3); /* Archivo de patrones: datos para train y para validacion */ fscanf(b, "%d", &PTOT); fscanf(b, "%d", &PR); fscanf(b, "%d", &PTEST); /* Parametros para el entrenamiento */ fscanf(b, "%d", &ITER); fscanf(b, "%f", &ETA); fscanf(b, "%f", &u); /* Datos para la salida de resultados */ fscanf(b, "%d", &NERROR); /* Inicializacion de las sinapsis - Azar o Archivo */ fscanf(b, "%d", &WTS); /* Semilla para la funcion rand() */ fscanf(b, "%d", &SEED); /* Nivel de verbosity */ fscanf(b, "%d", &CONTROL); /* Término de penalización (weight decay) */ fscanf(b, "%f", &GAMMA); fclose(b); /* Paso 2: Definir matrices para datos y pesos */ error = define_matrix(); if (error) { printf("Error en la definicion de matrices\n"); return 1; } /* Paso 3:leer sinapsis desde archivo o iniciar al azar */ if (WTS != 0) error = sinapsis_read(WTS); else sinapsis_rnd(0.1f); if (error) { printf("Error en la lectura de los pesos desde archivo\n"); return 1; } /* Imprimir control por pantalla */ printf("\nArquitectura de la red: %d:%d:%d", N1, N2, N3); printf("\nArchivo de patrones: %s", filename); printf("\nCantidad total de patrones: %d", PTOT); printf("\nCantidad de patrones de entrenamiento: %d", PR); printf("\nCantidad de patrones de validacion: %d", PTOT - PR); printf("\nCantidad de patrones de test: %d", PTEST); printf("\nEpocas: %d", ITER); printf("\nLearning Rate: %f", ETA); printf("\nMomentum: %f", u); printf("\nFrecuencia para grabar resultados: %d EPOCAS", NERROR); printf("\nArchivo con sinapsis iniciales: %d.WTS", WTS); printf("\nSemilla para la funcion rand(): %d", SEED); if (CONTROL) { printf("\nSINAPSIS:\n"); for (j = 1; j <= N2; j++) { for (i = 0; i <= N1; i++) printf("%f\n", w1[j][i]); } for (j = 1; j <= N3; j++) { for (i = 0; i <= N2; i++) printf("%f\n", w2[j][i]); } } return 0; } /* -------------------------------------------------------------------------------------- */ /*read_data: lee los datos de los archivos de entrenamiento(.data) y test(.test) filename es el nombre de los archivos (sin extension) La cantidad de datos y la estructura de los archivos fue leida en la funcion arquitec() Los registros en el archivo pueden estar separados por blancos ( o tab ) o por comas */ /* -------------------------------------------------------------------------------------- */ static int read_data(char *filename) { int i, k; FILE *fpat; float valor; int separador; sprintf(filepat, "%s.data", filename); fpat = fopen(filepat, "r"); error = (fpat == NULL); if (error) { printf("Error al abrir el archivo de datos\n"); return 1; } if (CONTROL > 1) printf("\n\nDatos de entrenamiento:"); for (k = 0; k < PTOT; k++) { if (CONTROL > 1) printf("\nP%d:\t", k); data[k][0] = -1.0f; for (i = 1; i <= N1 + N3; i++) { fscanf(fpat, "%f", &valor); data[k][i] = valor; if (CONTROL > 1) printf("%f\t", data[k][i]); separador = getc(fpat); if (separador != ',') ungetc(separador, fpat); } } fclose(fpat); if (!PTEST) return 0; sprintf(filepat, "%s.test", filename); fpat = fopen(filepat, "r"); error = (fpat == NULL); if (error) { printf("Error al abrir el archivo de test\n"); return 1; } if (CONTROL > 1) printf("\n\nDatos de test:"); for (k = 0; k < PTEST; k++) { if (CONTROL > 1) printf("\nP%d:\t", k); test[k][0] = -1.0f; for (i = 1; i <= N1 + N3; i++) { fscanf(fpat, "%f", &valor); test[k][i] = valor; if (CONTROL > 1) printf("%f\t", test[k][i]); separador = getc(fpat); if (separador != ',') ungetc(separador, fpat); } } fclose(fpat); return 0; } /* ------------------------------------------------------------ */ /* shuffle: mezcla el vector seq al azar. El vector seq es un indice para acceder a los patrones. Los patrones mezclados van desde seq[0] hasta seq[hasta-1] Esto permite separar la parte de validacion de la de train */ /* ------------------------------------------------------------ */ static void shuffle(int hasta) { float x; int tmp; int top, select; top = hasta - 1; while (top > 0) { x = (float)rand(); x /= (RAND_MAX + 1.0); x *= (top + 1); select = (int)x; tmp = seq[top]; seq[top] = seq[select]; seq[select] = tmp; top--; } if (CONTROL > 3) { printf("End shuffle\n"); fflush(NULL); } } /* ------------------------------------------------------------------- */ /*forward: propaga el vector de valores de entrada X1[] en la red En los vectores x2[] y x3[] quedan las activaciones correspondientes */ /* ------------------------------------------------------------------- */ static void forward() { int i, j, k; float h; /* calcular los X2 */ x2[0] = -1.0f; for (j = 1; j <= N2; j++) { h = 0.0f; for (k = 0; k <= N1; k++) h += w1[j][k] * x1[k]; x2[j] = sigmoid(h); } /* calcular los x3 */ for (i = 1; i <= N3; i++) { h = 0.0f; for (j = 0; j <= N2; j++) h += w2[i][j] * x2[j]; x3[i] = h; /* activacion lineal */ } if (CONTROL > 3) { printf("End forward\n"); fflush(NULL); } } /* ------------------------------------------------------------------------------ */ /*propagar: calcula los valores de salida de la red para un conjunto de datos la matriz S tiene que tener el formato adecuado ( definido en arquitec() ) pat_ini y pat_fin son los extremos a tomar en la matriz usar_seq define si se accede a los datos directamente o a travez del indice seq los resultados (las propagaciones) se guardan en la matriz seq */ /* ------------------------------------------------------------------------------ */ static float propagar(float **S, int pat_ini, int pat_fin, int usar_seq) { int i, j, k; float mse = 0.0f, mse_decay = 0.0f; int patron, nu; discrete_error = 0.f; for (patron = pat_ini; patron < pat_fin; patron++) { /* nu tiene el numero del patron que se va a presentar */ if (usar_seq) nu = seq[patron]; else nu = patron; /* cargar el patron en X1 */ for (i = 0; i <= N1; i++) x1[i] = S[nu][i]; /* propagar la red */ forward(); for (i = 1; i <= N3; i++) { /* generar matriz de predicciones */ pred[nu][i] = x3[i]; /* actualizar error estimado */ mse += (x3[i] - S[nu][N1 + i]) * (x3[i] - S[nu][N1 + i]); if (N3 == 1) if ((x3[i] - 0.5f) * (S[nu][N1 + i] - 0.5f) < 0.f) discrete_error += 1.0; /*calcula error discreto para una sola salida - problema binario */ } } /* weight decay */ for (j = 1; j <= N2; j++) for (k = 0; k <= N1; k++) mse_decay += w1[j][k] * w1[j][k]; for (i = 1; i <= N3; i++) for (j = 0; j <= N2; j++) mse_decay += w2[i][j] * w2[i][j]; mse /= ((float)(pat_fin - pat_ini)); mse += GAMMA * mse_decay; discrete_error /= (float)(pat_fin - pat_ini); if (CONTROL > 3) { printf("End prop\n"); fflush(NULL); } return mse; } /* --------------------------------------------------------------------------------------- */ /*train: entrena la red Algoritmo: Stochastic Back propagation Las salidas son las curvas de entrenamiento (mse estocastico,mse al final de la epoca, mse validacion, mse test) en el archivo .mse y la matriz final de sinapsis en el archivo (WTS+1).wts Los resultados finales y la matriz resultante corresponden al minimo de validacion si no hay validacion, corresponde al minimo de mse al final de la epoca */ /* ---------------------------------------------------------------------------------------- */ static int train(char *filename) { int i, j, k; FILE *ferror, *fpredic; int nu, nu1; int iter, epocas_del_minimo; float eta, decay, suma; float mse, mse_decay, mse_train, mse_valid, mse_test, minimo_valid; float disc_train, disc_valid, disc_test; /* Inicializar archivos de control */ sprintf(filepat, "%s.predic", filename); fpredic = fopen(filepat, "w"); error = (fpredic == NULL); if (error) { printf("Error al abrir archivo para guardar predicciones\n"); return 1; } sprintf(filepat, "%s.mse", filename); ferror = fopen(filepat, "w"); error = (ferror == NULL); if (error) { printf("Error al abrir archivo para guardar curvas\n"); return 1; } /* Inicializacion de todas las matrices */ for (j = 1; j <= N2; j++) { grad2[j] = 0.0f; for (k = 0; k <= N1; k++) dw1[j][k] = 0.0f; } for (i = 1; i <= N3; i++) { grad3[i] = 0.0f; for (j = 0; j <= N2; j++) dw2[i][j] = 0.0f; } for (k = 0; k < PTOT; k++) seq[k] = k; /* inicializacion del indice de acceso a los datos */ x1[0] = -1.0f; /* bias de las unidades de cada hilera */ x2[0] = -1.0f; minimo_valid = 1000000.0f; /* Fijar parametros: la nueva variable es para poder variar el learning rate durante el entrenamiento */ eta = ETA; decay = 1.f - 2.f * GAMMA * ETA; /*efectuar shuffle inicial de los datos de entrenamiento si SEED != -1 */ if (SEED > -1) { srand((unsigned)SEED); shuffle(PTOT); } /* for principal: ITER iteraciones */ for (iter = 1; iter <= ITER; iter++) { mse = 0.0f; mse_decay = 0.0f; shuffle(PR); /* barrido sobre los patrones de entrenamiento */ for (nu1 = 0; nu1 < PR; nu1++) { nu = seq[nu1]; /* nu tiene el numero del patron que se va a presentar */ /* cargar el patron en X1 */ for (k = 1; k <= N1; k++) x1[k] = data[nu][k]; /* propagar */ forward(); /* cargar los targets */ for (k = 1; k <= N3; k++) target[k] = data[nu][k + N1]; /* calcular gradiente en 3 hilera */ for (i = 1; i <= N3; i++) { grad3[i] = (target[i] - x3[i]); /*corresponde a lineal */ } /* calcular gradiente en 2 hilera */ for (j = 1; j <= N2; j++) { suma = 0.0f; for (i = 1; i <= N3; i++) suma += grad3[i] * w2[i][j]; grad2[j] = suma * (1.0f - x2[j]) * x2[j]; } /* calcular dw2 y corregir w2 */ for (i = 1; i <= N3; i++) for (j = 0; j <= N2; j++) { dw2[i][j] = u * dw2[i][j] + eta * grad3[i] * x2[j]; w2[i][j] *= decay; w2[i][j] += dw2[i][j]; mse_decay += w2[i][j] * w2[i][j]; } /* calcular dw1 y corregir w1 */ for (j = 1; j <= N2; j++) for (k = 0; k <= N1; k++) { dw1[j][k] = u * dw1[j][k] + eta * grad2[j] * x1[k]; w1[j][k] *= decay; w1[j][k] += dw1[j][k]; mse_decay += w1[j][k] * w1[j][k]; } /* actualizar el mse */ for (i = 1; i <= N3; i++) { mse += (x3[i] - target[i]) * (x3[i] - target[i]); } } /* next nu1 - barrido sobre patrones */ /* controles: grabar error cada NERROR iteraciones */ if ((iter / NERROR) * NERROR == iter) { mse /= ((float)PR); mse += GAMMA * mse_decay; mse_train = propagar(data, 0, PR, 1); disc_train = discrete_error; /* calcular mse de validacion; si no hay, usar mse_train */ if (PR == PTOT) { mse_valid = mse_train; disc_valid = disc_train; } else { mse_valid = propagar(data, PR, PTOT, 1); disc_valid = discrete_error; } /* calcular mse de test (si hay) */ if (PTEST > 0) { mse_test = propagar(test, 0, PTEST, 0); disc_test = discrete_error; } else mse_test = disc_test = 0.f; fprintf(ferror, "%f\t%f\t%f\t%f\t", mse, mse_train, mse_valid, mse_test); fprintf(ferror, "%f\t%f\t%f\t", disc_train, disc_valid, disc_test); fprintf(ferror, "%f\n", mse_decay * GAMMA); if (CONTROL) fflush(NULL); if (mse_valid < minimo_valid) { sinapsis_save(WTS + 1); minimo_valid = mse_valid; epocas_del_minimo = iter; } } if (CONTROL > 2) { printf("Iteracion %d\n", iter); fflush(NULL); } } /* next iter - lazo de iteraciones */ /* mostrar resumen del entrenamiento */ printf("\nFin del entrenamiento.\n\n"); printf("Error final:\nEntrenamiento(est):%f\nEntrenamiento(med):%f\n", mse, mse_train); printf("Validacion:%f\nTest:%f\n", mse_valid, mse_test); /* Calcular y guardar predicciones sobre el archivo de test */ /* leer pesos del minimo de validacion desde archivo */ sinapsis_read(WTS + 1); mse_test = propagar(test, 0, PTEST, 0); disc_test = discrete_error; for (k = 0; k < PTEST; k++) { for (i = 1; i <= N1; i++) fprintf(fpredic, "%f\t", test[k][i]); for (i = 1; i <= N3; i++) fprintf(fpredic, "%f\t", pred[k][i]); fprintf(fpredic, "\n"); } printf ("\nError minimo en validacion:\nEpoca:%d\nValidacion:%f\nTest:%f\nTest discreto:%f%%\n\n", epocas_del_minimo, minimo_valid, mse_test, 100.0 * disc_test); fclose(fpredic); fclose(ferror); return 0; } int main(int argc, char **argv) { if (argc != 2) { printf("Modo de uso: bp <filename>\n" "donde filename es el nombre del archivo (sin extension)\n"); return 0; } nameprefix = argv[1]; /* defino la red e inicializo los pesos */ error = arquitec(nameprefix); if (error) { printf("Error en la definicion de la red\n"); return 1; } /* leo los datos */ error = read_data(nameprefix); if (error) { printf("Error en la lectura de datos\n"); return 1; } /* entreno la red */ error = train(nameprefix); if (error) { printf("Error en el entrenamiento\n"); return 1; } return 0; }
C
#include<stdio.h> double Temperature(double n); int main(void) { double fah, kel; int val; printf("Please enter a temperature in Fahrenheit: "); val = scanf("%f", &fah); while (val == 1) { kel = Temperature(fah); printf("%.2f F = %.2f K\n", fah, kel); printf("Enter another temperature in Celsius (q or nonnumeric value to quit): "); val = scanf("%f", &fah); } return 0; } double Temperature(double n) { const double ABS = 273.16; const double REL = 32.0; const double FRA = 5.0 / 9.0; return FRA * ( n - REL ) + ABS; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "structs.h" #include "printer.h" #define MAX_BUFF 16 #define READ_STR "%15s" // ----- CREATORS FUNCTIONS Point *create_point(int x, int y); Map *create_map(int rows, int columns, FILE *input); // ---------------------------------------- // // docs // https://docs.google.com/document/d/1buH0mK6U_ZebSpookLaqd_0erx5hQUuMcuUff1sGtCo/edit#heading=h.rz194zb44u8t int main(int argc, char const *argv[]) { FILE *input; int x, y; Point *origin, *destiny, *step; input = fopen(argv[1], "r"); x = atoi(argv[2]); y = atoi(argv[3]); origin = create_point(x, y); x = atoi(argv[4]); y = atoi(argv[5]); destiny = create_point(x, y); x = atoi(argv[6]); y = atoi(argv[7]); step = create_point(x, y); int columns, rows; char str[MAX_BUFF]; fscanf(input, READ_STR, str); columns = atoi(str); fscanf(input, READ_STR, str); rows = atoi(str); Map *map; map = create_map(rows, columns, input); print_point_with(origin, "\norigin point"); print_point_with(destiny, "\ndestiny point"); print_point_with(step, "\nsteps"); print_map(map); fclose(input); return 0; } Point *create_point(int x, int y) { Point *point; point = malloc(sizeof(Point)); point->x = x; point->y = y; return point; } Map *create_map(int rows, int columns, FILE *input) { Map *map; int i, j; char str[MAX_BUFF]; map = malloc(sizeof(Map)); map->rows = rows; map->columns = columns; map->points = malloc(rows * sizeof(int*)); for(i=0; i<rows; i++) { map->points[i] = malloc(columns * sizeof(int)); for(j=0; j<columns; j++) { fscanf(input, READ_STR, str); map->points[i][j] = atoi(str); } } return map; }
C
/************************************************************************* * Nazev projektu: Prekladac jazyka IFJ 2015 * * Soubor: Instruction_list.j (pomocny soubor) * * Autor: Martin Švec * Datum: 19. listopadu 2015 * Popis: Soubor obsahuje deklarace pomocnych funkci pro praci s instrukci paskou. * Dale definuje pasku jako takovou. * *************************************************************************** */ #ifndef _Instruction_list_h #define _Instruction_list_h extern int errCode; extern void *conPtr; typedef enum { insCALL, // 0 // oznaceni kde se nachazi funkce (first je ukazatel na jmeno) insFUNSTART, // 1 // Aritmeticke operace insADD, insMUL, insSUB, insDIV, // 5 // Relacni operace insLESS, insLESSEQUAL, insEQUAL , insGREATER, insGREATEQUAL , insNOTEQUAL, //11 // 12 insMOV, // first: jmeno promene kam movnou vysledek // second: jmeno promene z ktere se ma prenaset // 13 14 insCIN, insCOUT, // first: jmeno promene vstupu/vystuou // 15 insJUMPZ, // first: string = jmeno promene ve ktere je vysledek; // second: ukazatel an instruci LABEL // 16 insJUMP, // first: ukazatel na instruci LABEL kam se ma skocit // 17 insLABEL // first: second: third: NULL POZOR: jedna se o prazdnou instrukci kterou je nutno prekocit } tName; typedef struct tIns { tName name; void *first, *second, *third; struct tIns * next; struct tIns *prev; } tIns; typedef struct { tIns *active; tIns *firstInsPtr; tIns *lastInsPtr; } tInstructionList; extern tInstructionList insList; void initInsList(); int createInsertIns(int name, void *first, void *second, void *third); int *allocCopyInt(int num); char *allocCopyString(char *str); double *allocCopyDouble(double decimal); #endif
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> /* Karakterler \0 > sonlandırıcı karakter (null character) \a > çan sesi (alert) \b > geri boşluk (back space) \t > 1 tane tab kadar boşluk bırakır. (horizontal TAB) \n > Bir alt satıra geçer(new line) \v > düşey tab (vertical tab) \f > sayfa ileri (form feed) \r > satır başı (carriage return) */ /* Veri Tipleri char-> int -> float -> double - char : Karakter(Character): Alfabedeki büyük küçük harfler, özel semboller //1 byte (-128'den 127'ye kadar) STANDART ASCII TABLOSU unsigned char > İşaretsiz char Türü - int : Tamsayı(İnteger): Tamsayı değişken ve sabitleri tanımlamak için kullanılır. //4 byte [signed] short [int] > İşaretli Kısa Tamsayı Türü // 2 byte (-32.768 - 32.767) [signed] long [int] > İşaretli Uzun Tamsayı Türü // 4 byte (-2.147.483.648 - 2.147.483.647) unsigned short [int] > İşaretsiz Kısa Tamsayı Türü // 2 byte unsigned long [int] > İşaretsiz Uzun Tamsayı Türü // 4 byte - float : Küsüratlı Sayılar: Virgüllü kısmıyla ifade eder. //4 byte - double : Daha Hassas Küsüratlı Sayılar: Float türünden 2 kat daha duyarlıdır. //8 byte long double */ /* Yer ve Tür Belirleyiciler Yer Belirleyicileri - auto - register - static - extern Tür Belirleyicileri - const > Bir değişken ile tanımlandığında ve ilk değer atandığında, bu değişken içeriği hiç değişmez. ÖRN: const pi = 3.14; const double pi = 3.1416; - volatile */ int main() { setlocale(LC_ALL, "Turkish"); int tamsayi; char karakter; char karakterDizisi[50]; float kesirlisayi1; double kesirlisayi2; /* scanf veri alır, printf veri gönderir*/ printf("Lütfen bir tam sayı giriniz: "); scanf("%d", &tamsayi); printf("Lütfen bir karakter giriniz: "); scanf(" %c", &karakter); /* scanf(" %c" ,&karakter); Program içerisinde kullanıcıdan birden fazla tipte değer almak istediğimizde derleyicinin kafasının karışmaması için karakter alırken bir boşluk kullanarak karakter değerini kullanıcıdan almalıyız. */ printf("Lütfen bir karakter dizini giriniz: "); scanf("%s", &karakterDizisi); // scanf("%s" ,&karakterDizisi), scanf("%s" ,karakterDizisi), scanf("%s" ,karakterDizisi[0]) printf("Lütfen bir kesirli sayı giriniz: "); // Program bizden kesirli bir sayı değeri girmemizi istediğinde virgül kullanarak girmeliyiz. scanf("%f", &kesirlisayi1); printf("Lütfen bir daha hassas küsüratlı bir sayı giriniz: "); scanf("%lf", &kesirlisayi2); /* printf ("Sabit metin bilgisi", değişken ismi)*/ printf("\n\n"); printf("Girilen Tam Sayı: %d\n", tamsayi); printf("Girilen Karakter: %c\n", karakter); printf("Girilen Karakter Dizisi: %s\n", karakterDizisi); printf("Girilen Kesirli Sayı: %f\n", kesirlisayi1); printf("Girilen Hassas Küsüratlı Sayı: %lf\n", kesirlisayi2); int x = 15; float y = 15; double z = 15; printf("\n\n"); printf("int / float= %f\n", x / y); printf("int / float= %lf\n", x / z); printf("float / double= %f\n", y / z); int t = 3; printf("\n\n"); printf("%f\n", (float)x); printf("%.1f", (float)x); }
C
#include<stdio.h> #include<conio.h> double getfloat(); int main() /*Main is written to check the getfloat function*/ { double num; num = getfloat(); printf("\nNumber : %lf\n", num); _getch(); return 0; } double getfloat() { double num = 0; char number[20]; scanf("%s", number); sscanf(number, "%lf", &num); return num; }
C
#include <stdio.h> #include <locale.h> void main() { int num1, num2; setlocale(LC_ALL,"Portuguese"); printf("Me diga dois nmeros e eu colocarei \n"); printf(" os dois em ordem crescente \n"); printf("\n Primeiro nmero: "); scanf("%d",&num1); printf("\n Segundo nmero: "); scanf("%d",&num2); if (num1<num2) { printf("Os nmeros em ordem so %d e %d",num1,num2); }else { if(num1>num2) { printf("Os nmeros em ordem so %d e %d",num2,num1); } } }
C
#include "fila.h" int Menu(); void Coloca(); void Tira(); Aluno a; int main(){ init(); Menu(); } int Menu() { int resp; while(TRUE) { printf("\n---------------------------------------\n1-Colocar Aluno\n2-Retirar Aluno\n3-Terminar\n---------------------------------------\nDigite:"); scanf("%i",resp); switch(resp) { case(1): Coloca(); Menu(); case(2): Tira(); Menu(); case(3): printf("\nLiberar alunos\n"); finish(); return 0; } } } void Coloca() { printf("nome? "); scanf("%s", a.nome); printf("nota? "); scanf("%f", &a.nota); entra(a); } void Tira() { printf("\n fila de alunos\n"); while(vazia()==FALSE){ sai(&a); printf("%s %f\n", a.nome, a.nota); } }
C
/* * ===================================================================================== * * Filename: stdio.c * * Description: 输入输出函数的定义与实现 * * Version: 1.0 * Created: 2014年11月17日 20时45分19秒 * Revision: none * Compiler: gcc * * Author: Shui(dubingyang), [email protected] * Company: Class 1201 of software engineering * * ===================================================================================== */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include <console.h> #include <x86.h> /*@putchar:显示一个字符,默认颜色为黑底白字 *@v, 要输出的字符 * */ void putchar(int c) { console_putc(c); } /*@puts:要输出一个字符串 *@str, 要输出字符串的首地址 * */ int puts(const char *str) { int count = 0; char c; while ((c = *str ++) != '\0') { console_putc(c); count++; } return count; } /*@getint 获得有符号类型的整型的值,从栈的列表中 * *@ap: 栈的指针 *@lfag:ap指向的数值的大小 */ static long long getint(va_list *ap, int lflag) { if (lflag >= 2) { return va_arg(*ap, long long); } else if (lflag) { return va_arg(*ap, long); } else { return va_arg(*ap, int); } } /*@getuint 获得无符号类型的整型的值,从栈的列表中 * *@ap: 栈的指针 *@lfag:ap指向的数值的大小 */ static long long getuint(va_list *ap, int lflag) { if (lflag >= 2) { return va_arg(*ap, unsigned long long); } else if (lflag) { return va_arg(*ap, unsigned long); } else { return va_arg(*ap, unsigned int); } } /*@printknum将数字解析并输出 *@num:将要输出的数 *@width:输出数字的宽度 *@padc:右对齐还是用0补充 *@base:要输出的数字的进制 */ void printknum(unsigned long long num, int width, char padc, int base) { unsigned long long n = num; unsigned mod = do_div(n, base); if (num >= base) { printknum(n, width - 1, padc, base); } else { while (--width > 0) { putchar(padc); } } putchar("0123456789abcdef"[mod]); } /*@vprintf:格式化输出函数调用的函数式 *@fmt:格式化字符串 *@ap指向函数的第二个参数的首地址 * */ int vprintk(const char *fmt, va_list ap) { int ch; int count = 0; const char *p; int base; //输出的机制 char padc; unsigned long long num; //表示要打印的 int width, lfag, altflag; int precison; while (true) { while ((ch = *(unsigned char *)fmt ++) != '%') { if (ch == '\0') { return count; } count++; putchar(ch); } padc = ' '; width = precison = -1; lfag = altflag = 0; while (true) { switch(ch = *(unsigned char *)fmt ++) { case '-': padc = '-'; continue; case '0': padc = '0'; continue; case '*': precison = va_arg(ap, int); if (width < 0) { width = precison; precison = -1; } continue; case '1' ... '9': for (precison = 0; ; ++fmt) { precison = precison * 10 + ch - '0'; ch = *fmt; if (ch < '0' || ch > '9') { break; } } if (width < 0) { width = precison; precison = -1; } continue; case '#': altflag = 1; continue; case '.': if (width < 0) { width = 0; } continue; //long long int case 'l': lfag++; continue; //character case 'c': putchar(va_arg(ap, char)); count++; break; case 's': if ((p = va_arg(ap, char *)) == NULL) { p = "(NULL)"; } //右对齐用来对齐的 if (width > 0 && padc != '-') { for (width -= strnlen(p, precison); width > 0; width--) { putchar(padc); } } for (; (ch = *p++) != '\0'&&(precison < 0 || --precison >= 0); width--) { putchar(ch); } //左对齐的 for (; width > 0; --width) { putchar(' '); } break; case 'd': num = getint(&ap, lfag); if ((long long)num < 0 ) { putchar('-'); num = -(long long) num; } base = 10; printknum(num, width, padc, base); count++; break; case 'u': num = getuint(&ap, lfag); base = 10; printknum(num, width, padc, base); count++; break; case 'o': num = getuint(&ap, lfag); base = 8; printknum(num, width, padc, base); count++; break; case 'x': putchar('0'); putchar('x'); num = getuint(&ap, lfag); base = 16; printknum(num, width, padc, base); count++; break; case 'p': putchar('0'); putchar('x'); num = (unsigned long long)(unsigned int )va_arg(ap, void *); base = 16; printknum(num, width, padc, base); count++; break; case '%': putchar(ch); count++; break; default: putchar(ch); // for (ch--; ch[-1] != '%'; --ch) { // putchar(ch); // } break; } break; } } } /*@printk:格式化输出的函数式 *@fmt:格式化的字符串 *压栈的顺序是从右到左的顺序,但是参数中的表达式,在计算顺序中C语言并没有保证 * */ int printk(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintk(fmt, ap); return 0; } //void snprintk(char *str, size_t size, const char *fmt, ...); //void vsnprintk(char *str, size_t, const char *fmt, va_list ap);
C
#define _XOPEN_SOURCE #include <stdio.h> #include <stdlib.h> //#include <pthread.h> #include <unistd.h> #include <string.h> //#include <crypt.h> tylko dla crypt_r int main(int argc, char ** argv) { char * pass = NULL; char * salt = NULL; int opt; opterr = 0; while((opt = getopt(argc, argv, "p:s:"))!= -1) { switch(opt) { case 'p': pass = optarg; printf("pass:%s\n", pass); break; case 's': salt = (char *)malloc(sizeof("$6$") + sizeof(optarg) + sizeof("$") + 1); strcpy(salt, "$6$"); strcat(salt, optarg); strcat(salt, "$"); printf("salt:%s\n", optarg); break; default: fprintf(stderr, "BAD BOY\n"); exit(EXIT_FAILURE); } } if((pass == NULL) || (salt == NULL)) { fprintf(stdout, "Zla liczba argumentow.\nnp. ./a.out -p [haslo] -s [domieszka].\n"); exit(1); } char * res = crypt(pass, salt); if(res == NULL) { fprintf(stdout, "sie zesralo.\n"); exit(1); } fprintf(stdout, "Haslo: %s, Domieszka: %s\nWynik: %s\n",pass,salt,res); char * hash = (char *)malloc(86+1);//taki rozmiar w manualu strncpy(hash, res + strlen(salt), 86); fprintf(stdout, "Hash: %s\n",hash); free(res); free(hash); free(salt); exit(0); }
C
/* * throttle_data.c * * Created on: Mar 8, 2017 * Author: xuefei1 * * Status: C */ #include "throttle_data.h" //index 0 to 90, representing 0 to 90 degree of throttle plate travel //the value at index i and value at index i+1 indicates if APPS value is within this range //then the throttle plate will be at i+1 degrees //if apps reading value == value at index i, then throttle plate is at i degrees INT16U throttle_deg_apps_val_map[MAX_THROTTLE_DEG + 1]; //same idea as above INT16U throttle_deg_tps_val_map[MAX_THROTTLE_DEG + 1]; //value at index i represents the duty cycle needed for the 20 kHz signal to open the throttle //throttle resolution could be less than 1 deg, in that case, many degress could have the same //duty cycle value //remember this duty cycle only controls opening of throttle plate //to close the plate, we need a pwm signal with different polarity and a feedback system is used INT16U throttle_deg_open_pwm_duty_cycle[MAX_THROTTLE_DEG + 1]; void throttle_data_init(){ INT16U apps_val_inc_by_1_deg = (APPS_VALID_VALUE_FULLY_PRESSED - APPS_VALID_VALUE_FULLY_RELEASED) / MAX_THROTTLE_DEG; INT16U tps_val_inc_by_1_deg = (TPS_VALID_VALUE_FULLY_OPENED - TPS_VALID_VALUE_FULLY_CLOSED) / MAX_THROTTLE_DEG; INT16U deg_inc_by_1_percent_duty = MAX_THROTTLE_DEG / (MOTOR_PWM_DUTY_CYCLE_FULLY_CLOSE - MOTOR_PWM_DUTY_CYCLE_FULLY_OPEN) + 1; INT16U i; throttle_deg_apps_val_map[0] = APPS_VALID_VALUE_FULLY_RELEASED; throttle_deg_tps_val_map[0] = TPS_VALID_VALUE_FULLY_CLOSED; throttle_deg_open_pwm_duty_cycle[0] = MOTOR_PWM_DUTY_CYCLE_FULLY_CLOSE; for(i=1; i<MAX_THROTTLE_DEG; i++){ throttle_deg_apps_val_map[i] = throttle_deg_apps_val_map[i - 1] + apps_val_inc_by_1_deg; throttle_deg_tps_val_map[i] = throttle_deg_tps_val_map[i - 1] + tps_val_inc_by_1_deg; if(i % deg_inc_by_1_percent_duty == 0){ throttle_deg_open_pwm_duty_cycle[i] = throttle_deg_open_pwm_duty_cycle[i-1] - 1; // decrease duty cycle }else{ throttle_deg_open_pwm_duty_cycle[i] = throttle_deg_open_pwm_duty_cycle[i-1]; } } throttle_deg_apps_val_map[MAX_THROTTLE_DEG] = APPS_VALID_VALUE_FULLY_PRESSED; throttle_deg_tps_val_map[MAX_THROTTLE_DEG] = TPS_VALID_VALUE_FULLY_OPENED; throttle_deg_open_pwm_duty_cycle[MAX_THROTTLE_DEG] = MOTOR_PWM_DUTY_CYCLE_FULLY_OPEN; } INT16U get_throttle_open_deg_from_apps(INT16U apps_reading){ if(apps_reading >= APPS_VALID_VALUE_FULLY_PRESSED){ return MAX_THROTTLE_DEG; } if(apps_reading <= APPS_VALID_VALUE_FULLY_RELEASED){ return MIN_THROTTLE_DEG; } INT8U upper; for(upper = 1; upper < MAX_THROTTLE_DEG; upper++){ if(apps_reading <= throttle_deg_apps_val_map[upper] && apps_reading > throttle_deg_apps_val_map[upper - 1]){ return upper; } } return MAX_THROTTLE_DEG; } INT16U get_tps_from_apps(INT16U apps_reading){ if(apps_reading >= APPS_VALID_VALUE_FULLY_PRESSED){ return throttle_deg_tps_val_map[MAX_THROTTLE_DEG]; } if(apps_reading <= APPS_VALID_VALUE_FULLY_RELEASED){ return throttle_deg_tps_val_map[MIN_THROTTLE_DEG]; } INT8U upper; for(upper = 1; upper < MAX_THROTTLE_DEG; upper++){ if(apps_reading <= throttle_deg_apps_val_map[upper] && apps_reading > throttle_deg_apps_val_map[upper - 1]){ return throttle_deg_tps_val_map[upper]; } } return throttle_deg_tps_val_map[MAX_THROTTLE_DEG]; } INT16U get_throttle_open_deg_from_tps(INT16U tps_reading){ if(tps_reading >= TPS_VALID_VALUE_FULLY_OPENED){ return MAX_THROTTLE_DEG; } if(tps_reading <= TPS_VALID_VALUE_FULLY_CLOSED){ return MIN_THROTTLE_DEG; } INT8U upper; for(upper = 1; upper < MAX_THROTTLE_DEG; upper++){ if(tps_reading <= throttle_deg_tps_val_map[upper] && tps_reading > throttle_deg_tps_val_map[upper - 1]){ return upper; } } return MAX_THROTTLE_DEG; } //input param: the degree you want the throttle to OPEN by INT16U get_duty_cycle_from_throttle_open_deg(INT16U deg){ if(deg > MAX_THROTTLE_DEG){ deg = MAX_THROTTLE_DEG; } return throttle_deg_open_pwm_duty_cycle[deg]; } INT16U get_duty_cycle_from_throttle_close_deg(INT16U deg){ return throttle_deg_open_pwm_duty_cycle[MOTOR_PWM_DUTY_CYCLE_FULLY_OPEN]; } INT16U get_tps_from_throttle_open_deg(INT16U deg){ if(deg > MAX_THROTTLE_DEG){ deg = MAX_THROTTLE_DEG; } return throttle_deg_tps_val_map[deg]; }
C
//4 #include <stdio.h> int main () { int x, result; while (1) { printf("Enter a mark: "); result = scanf("%d", &x); if (result) { if (x == 0) { break; } if (x > 100 || x < 0) { printf("Wrong Mark:%d\n" , x); } } } }
C
#include <stdio.h> // Needed for exit() #include <stdlib.h> #include <string.h> void doWhile(); int globalVar = 0; int main() { char name[17]; printf("What's your name? "); fgets(name, 30, stdin); printf("Hello %s\n\n", name); printf("\n"); char wholeName[17] = "Satoshi Nakamoto"; int primeNumbers[3] = {2, 3, 5}; int morePrimes[] = {13, 17, 19, 23}; printf("The first prime in the list is %d\n\n", primeNumbers[0]); char city[7] = {'C', 'h', 'i', '\0'}; char thirdCity[] = "Paris"; char yourCity[30]; printf("What city do you live in? "); fgets(yourCity, 30, stdin); printf("Hello %s\n\n", yourCity); for (int i = 0; i < 30; i++) { if (yourCity[i] == '\n') { yourCity[i] = '\0'; break; } } printf("Hello %s\n\n", yourCity); printf("Is your city Paris? %d\n\n", strcmp(yourCity, thirdCity)); char yourState[] = ", Pensylvania"; strcat(yourCity, yourState); printf("You live in %s\n\n", yourCity); printf("Letters in Paris: %lu\n\n", strlen(thirdCity)); strlcpy(yourCity, "El Pueblo del la Reina de Los Angeles", sizeof(yourCity)); printf("New City is %s\n\n", yourCity); doWhile(); return 0; } void doWhile() { int doWhileOrNot = 0; printf("Do you want to try do while? 0) No 1) Yes "); scanf(" %d", &doWhileOrNot); if (doWhileOrNot == 1) { int whatToDo; printf("First do while\n"); do{ printf("\n"); printf("1. What time is it?\n"); printf("2. What is todays date?\n"); printf("3. What day is it?\n"); printf("4. Quit\n"); scanf(" %d", &whatToDo); } while(whatToDo < 1 || whatToDo > 4); if(whatToDo == 1) printf("Print the time\n"); else if(whatToDo == 2) printf("Print the date\n"); else if(whatToDo == 3) printf("Print the day\n"); else { printf("Bye Bye\n"); exit(0); } printf("Second do while\n"); do{ printf("\n"); printf("1. What time is it?\n"); printf("2. What is todays date?\n"); printf("3. What day is it?\n"); printf("4. Quit\n"); scanf(" %d", &whatToDo); } while(whatToDo < 1 || whatToDo > 4); switch(whatToDo) { case(1): printf("Print the time\n"); break; case(2): printf("Print the date\n"); break; case(3): printf("Print the day\n"); break; default: printf("Bye\n"); exit(0); break; } } }
C
#include "HAL_GPIO.h" /*************MODER configuration*************/ static void HAL_Config_Mode(GPIO_TypeDef *port , uint32_t pinNumber , uint32_t mode_type) { uint32_t bitNumber; bitNumber = pinNumber * 2; // Bit number for GPIO MODE register switch(mode_type) { // (0b00) case INPUT_ANALOG: port->MODER &= ~( (1<<bitNumber) | (1<<(bitNumber + 1)) ); // Reset bits bitNum and (bitNum + 1) break; // (0b01) case OUTPUT_GENERAL: port->MODER |= (1<<bitNumber); // Set bit bitNum port->MODER &= ~(1<<(bitNumber + 1)); // Reset bit (bitNum + 1) break; // (0b10) case ALT_FUN: port->MODER &= ~(1<<(bitNumber)); // Reset bit bitNum port->MODER |= (1<<(bitNumber + 1)); // Set bit (bitNum + 1) break; // (0b11) case AN_MODE: port->MODER |= ( (1<<bitNumber) | (1<<(bitNumber + 1)) ); // Set bits bitNum and (bitNum + 1) break; }// end mode type switch } /********************************************/ /***********OSPEEDR configuration************/ static void HAL_Config_Speed(GPIO_TypeDef *port, uint32_t pinNumber, uint32_t pinSpeed) { uint32_t bitNumber = pinNumber * 2; switch(pinSpeed) { // (0b00) case SPEED_LOW: port->OSPEEDR &= ~( (1<<bitNumber) | (1<<(bitNumber + 1)) ); // Clear bits bitNum and (bitNum + 1) break; // (0b01) case SPEED_MEDIUM: port->OSPEEDR |= (1<<bitNumber); // Set bit bitNumber port->OSPEEDR &= ~(1<<(bitNumber + 1)); // Clear bit (bitNum + 1) break; // (0b10) case SPEED_HIGH: port->OSPEEDR &= ~(1<<bitNumber); // Clear bit bitNumber port->OSPEEDR |= (1<<(bitNumber + 1)); // Set bit (bitNumber + 1) break; // (0b11) case SPEED_VHIGH: port->OSPEEDR |= ( (1<<bitNumber) | (1<<(bitNumber + 1)) ); // Set bits bitNum and (bitNum + 1) break; }// end speed type switch } /********************************************/ /***********OTYPER configuration*************/ static void HAL_Config_Otype(GPIO_TypeDef *port, uint32_t pinNumber, uint32_t pinOtype) { switch(pinOtype) { // Output push-pull case OUTPUT_PP: port->OTYPER &= ~(1<<pinNumber); // Clear bit pinNumber break; case OUTPUT_OPEN: port->OTYPER |= (1<<pinNumber); // Set bit pinNumber break; }// end output type switch } /********************************************/ /***********PUPDR configuration**************/ static void HAL_Config_Pupd(GPIO_TypeDef *port, uint32_t pinNumber, uint32_t pupdMode) { uint32_t bitNumber = pinNumber * 2; switch(pupdMode) { case PUPD_NONE: port->PUPDR &= ~( (1<<bitNumber) | (1<<(bitNumber + 1)) ); // Reset bits bitNum and (bitNum + 1) break; case PUPD_PU: port->PUPDR |= (1<<bitNumber); // Set bit bitNumber port->PUPDR &= ~(1<<(bitNumber + 1)); // Clear bit (bitNumber + 1) break; case PUPD_PD: port->PUPDR &= ~(1<<bitNumber); // Clear bit bitNumber port->PUPDR |= (1<<(bitNumber + 1)); // Set bit bitNumber break; case PUPD_RESERVED: port->PUPDR |= ( (1<<bitNumber) | (1<<(bitNumber + 1)) ); // Set bits bitNumber and (bitNumber + 1) break; }// end pupd switch } /***********BSRR configuration****************/ void GPIO_Write(GPIO_TypeDef *port, uint32_t pinNumber, uint32_t state) { if(state) { port->BSRR = (1<<pinNumber); } else { port->BSRR = (1<<(pinNumber + 16)); } } /***********BSRR configuration****************/ void GPIO_Toggle(GPIO_TypeDef *port, uint32_t pinNumber) { port->ODR ^=(1<<pinNumber); } /***********CLOCK initialization**************/ void GPIO_Init(GPIO_TYPE gpio_type) { if(gpio_type.port == PORTA) GPIO_CLOCK_ENABLE_PORTA; if(gpio_type.port == PORTB) GPIO_CLOCK_ENABLE_PORTB; if(gpio_type.port == PORTC) GPIO_CLOCK_ENABLE_PORTC; if(gpio_type.port == PORTD) GPIO_CLOCK_ENABLE_PORTD; if(gpio_type.port == PORTE) GPIO_CLOCK_ENABLE_PORTE; HAL_Config_Mode(gpio_type.port, gpio_type.pin, gpio_type.mode); HAL_Config_Otype(gpio_type.port, gpio_type.pin, gpio_type.out_type); HAL_Config_Pupd(gpio_type.port, gpio_type.pin, gpio_type.pull); HAL_Config_Speed(gpio_type.port, gpio_type.pin, gpio_type.speed); } /***********Interrupt initialization***********/ void INTERRUPT_GPIO_Config(GPIO_TypeDef *port, uint32_t pinNumber, edge_select edge) { // Enable SYSCFG and used PORT clocks RCC->APB2ENR = RCC_APB2ENR_SYSCFGEN; if(port == PORTA) { GPIO_CLOCK_ENABLE_PORTA; switch(pinNumber) { // Configure the appropriate EXTI registers for each pin case 0: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PA; break; case 1: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI1_PA; break; case 2: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI2_PA; break; case 3: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI3_PA; break; case 4: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI4_PA; break; case 5: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI5_PA; break; case 6: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI6_PA; break; case 7: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI7_PA; break; case 8: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI8_PA; break; case 9: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI9_PA; break; case 10: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI10_PA; break; case 11: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI11_PA; break; case 12: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI12_PA; break; case 13: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI13_PA; break; case 14: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI14_PA; break; case 15: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI15_PA; break; } } if(port == PORTB) { GPIO_CLOCK_ENABLE_PORTB; switch(pinNumber) { // Configure the appropriate EXTI registers for each pin case 0: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PB; break; case 1: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI1_PB; break; case 2: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI2_PB; break; case 3: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI3_PB; break; case 4: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI4_PB; break; case 5: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI5_PB; break; case 6: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI6_PB; break; case 7: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI7_PB; break; case 8: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI8_PB; break; case 9: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI9_PB; break; case 10: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI10_PB; break; case 11: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI11_PB; break; case 12: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI12_PB; break; case 13: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI13_PB; break; case 14: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI14_PB; break; case 15: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI15_PB; break; } } if(port == PORTC) { GPIO_CLOCK_ENABLE_PORTC; switch(pinNumber) { // Configure the appropriate EXTI registers for each pin case 0: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PC; break; case 1: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI1_PC; break; case 2: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI2_PC; break; case 3: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI3_PC; break; case 4: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI4_PC; break; case 5: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI5_PC; break; case 6: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI6_PC; break; case 7: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI7_PC; break; case 8: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI8_PC; break; case 9: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI9_PC; break; case 10: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI10_PC; break; case 11: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI11_PC; break; case 12: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI12_PC; break; case 13: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI13_PC; break; case 14: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI14_PC; break; case 15: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI15_PC; break; } } if(port == PORTD) { GPIO_CLOCK_ENABLE_PORTD; switch(pinNumber) { // Configure the appropriate EXTI registers for each pin case 0: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PD; break; case 1: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI1_PD; break; case 2: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI2_PD; break; case 3: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI3_PD; break; case 4: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI4_PD; break; case 5: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI5_PD; break; case 6: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI6_PD; break; case 7: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI7_PD; break; case 8: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI8_PD; break; case 9: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI9_PD; break; case 10: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI10_PD; break; case 11: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI11_PD; break; case 12: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI12_PD; break; case 13: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI13_PD; break; case 14: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI14_PD; break; case 15: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI15_PD; break; } } if(port == PORTE) { GPIO_CLOCK_ENABLE_PORTE; switch(pinNumber) { // Configure the appropriate EXTI registers for each pin case 0: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI0_PE; break; case 1: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI1_PE; break; case 2: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI2_PE; break; case 3: SYSCFG->EXTICR[0] = SYSCFG_EXTICR1_EXTI3_PE; break; case 4: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI4_PE; break; case 5: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI5_PE; break; case 6: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI6_PE; break; case 7: SYSCFG->EXTICR[1] = SYSCFG_EXTICR2_EXTI7_PE; break; case 8: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI8_PE; break; case 9: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI9_PE; break; case 10: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI10_PE; break; case 11: SYSCFG->EXTICR[2] = SYSCFG_EXTICR3_EXTI11_PE; break; case 12: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI12_PE; break; case 13: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI13_PE; break; case 14: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI14_PE; break; case 15: SYSCFG->EXTICR[3] = SYSCFG_EXTICR4_EXTI15_PE; break; } } if(edge == RISING_EDGE) { EXTI->RTSR |= (1<<pinNumber); } if(edge == FALLING_EDGE) { EXTI->FTSR |= (1<<pinNumber); } if(edge == RISING_FALLING_EDGE) { EXTI->RTSR |= (1<<pinNumber); EXTI->FTSR |= (1<<pinNumber); } } /*************INTERRUPT enable*************/ void INTERRUPT_GPIO_Enable(uint32_t pinNumber, IRQn_Type irqNumber) { // Enable interrupt in EXTI EXTI->IMR |= (1<<pinNumber); // Enable interrupt in NVIC NVIC_EnableIRQ(irqNumber); } /************INTERRUPT clear***************/ void INTERRUPT_GPIO_Clear(uint32_t pinNumber) { EXTI->PR |= (1<<pinNumber); }
C
/************************************************************************* > File Name : acm1029.c > Author : enjoy5512 > Mail : [email protected] > Created Time : 2016年12月20日 星期二 14时53分46秒 ************************************************************************/ #include <stdio.h> #include <string.h> int main(int argc,char *argv[]) { char ch = 0; int i = 0; char check[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; int tmp = 0; while(1) { ch = getchar(); if ('$' == ch) { printf("\n"); break; } else if (10 == ch) { printf("\n"); i = 0; } else { i++; if (ch-65-i%26 < 0) { printf("%c", check[26+ch-65-i%26]); } else { printf("%c", check[ch-65-i%26]); } } } return 0; }
C
/*############################################################################### Kodierung: UTF-8 ohne BOM ###############################################################################*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include "vektoren.h" #include "eingaben.h" #include "generator.h" #include "analysen.h" #include "matrizen.h" #include "vektoren.c" #include "eingaben.c" #include "generator.c" #include "analysen.c" #include "matrizen.c" //############################################################################### /** Das Programm dient der wahlweisen Berechnung (Addition,Subtraktion, Multiplikation) manuell erfasster oder zufällig generierter Matrizen. @author Thomas Gerlach @version 1.0 **/ //############################################################################### int main(void) { zufall_initialisieren(); do { system("clear"); printf("\n\n\tM a t r i z e n\n\n"); printf("Ich erfasse oder erzeuge und addiere, subtrahiere oder multipliziere Matrizen.\n\n"); int dimension = erfasse_ganzzahl("Dimension der Matrizen (1 <= n <= 10)", 1, 10); int anzahl = dimension * dimension; int *matrix_a = NULL; int *matrix_b = NULL; int *matrix_c = NULL; switch (erfasse_ganzzahl("Erfassung der Werte manuell (1) oder zufällig (2) ?", 1, 2)) { case 1: matrix_a = matrix_ganzzahl_werte_erfassen("Erfasse Matrix A", dimension, dimension, -1000, 1000); matrix_b = matrix_ganzzahl_werte_erfassen("Erfasse Matrix B", dimension, dimension, -1000, 1000); break; case 2: matrix_a = liste_ganzzahl_zufall_schreiben(liste_ganzzahl_erstellen(anzahl), anzahl, -1000, 1000); matrix_b = liste_ganzzahl_zufall_schreiben(liste_ganzzahl_erstellen(anzahl), anzahl, -1000, 1000); break; } do { system("clear"); liste_ganzzahl_matrix_ausgeben("Matrix A", matrix_a, anzahl, dimension, 6); liste_ganzzahl_matrix_ausgeben("Matrix B", matrix_b, anzahl, dimension, 6); switch (erfasse_ganzzahl("Rechenart Addition (1) Subtraktion (2) Multiplikation (3) ?", 1, 3)) { case 1: matrix_c = matrix_ganzzahl_addieren(matrix_a, matrix_b, dimension); break; case 2: matrix_c = matrix_ganzzahl_subtrahieren(matrix_a, matrix_b, dimension); break; case 3: matrix_c = matrix_ganzzahl_multiplizieren(matrix_a, matrix_b, dimension); break; } liste_ganzzahl_matrix_ausgeben("Matrix C", matrix_c, anzahl, dimension, 10); free(matrix_c); } while (erfasse_antwort("\nOperation erneut wählen? (j/n)")); free(matrix_a); free(matrix_b); } while (erfasse_antwort("\n\nNoch einmal? (j/n)")); printf("\n\n\tAuf Wiedersehen!\n\n"); }
C
#include <stdio.h> #include <stdlib.h> #include "stack.h" int main() { int i; int a[10] = {12,4354,657,876,2433,23,18,943,54,8}; Stack S = malloc(sizeof(struct Node)); S = CreateStack(); for(i=0;i<8;i++){ Push(a[i],S); } Pop(S); int b = Top(S); printf("the top value is:%d \n", b); if(IsEmpty(S)) { printf("The Stack is empty!\n"); exit(1); }else{ printf("The Stack is not empty!\n"); } PrintStack(S); return 0; }
C
/* PostScript graphics - * This provides a bit of a shell around writing graphics to * a postScript file. Perhaps the most important thing it * does is convert 0,0 from being at the bottom left to * being at the top left. */ #ifndef PSGFX_H #define PSGFX_H #include "psPoly.h" struct psGfx /* A postScript output file. */ { FILE *f; /* File to write to. */ double userWidth, userHeight; /* Size of image in virtual pixels. */ double ptWidth, ptHeight; /* Size of image in points (1/72 of an inch) */ double xScale, yScale; /* Conversion from pixels to points. */ double xOff, yOff; /* Offset from pixels to points. */ double fontHeight; /* Height of current font. */ }; struct psGfx *psOpen(char *fileName, double userWidth, double userHeight, /* Dimension of image in user's units. */ double ptWidth, double ptHeight, /* Dimension of image in points. */ double ptMargin); /* Image margin in points. */ /* Open up a new postscript file. If ptHeight is 0, it will be * calculated to keep pixels square. */ void psClose(struct psGfx **pPs); /* Close out postScript file. */ void psTranslate(struct psGfx *ps, double xTrans, double yTrans); /* add a constant to translate all coordinates */ void psSetLineWidth(struct psGfx *ps, double factor); /* Set line width to factor * a single pixel width. */ void psClipRect(struct psGfx *ps, double x, double y, double width, double height); /* Set clipping rectangle. */ void psDrawBox(struct psGfx *ps, double x, double y, double width, double height); /* Draw a filled box in current color. */ void psDrawLine(struct psGfx *ps, double x1, double y1, double x2, double y2); /* Draw a line from x1/y1 to x2/y2 */ void psFillUnder(struct psGfx *ps, double x1, double y1, double x2, double y2, double bottom); /* Draw a 4 sided filled figure that has line x1/y1 to x2/y2 at * it's top, a horizontal line at bottom at it's bottom, and * vertical lines from the bottom to y1 on the left and bottom to * y2 on the right. */ void psXyOut(struct psGfx *ps, double x, double y); /* Output x,y position transformed into PostScript space. * Useful if you're mixing direct PostScript with psGfx * functions. */ void psWhOut(struct psGfx *ps, double width, double height); /* Output width/height transformed into PostScript space. */ void psMoveTo(struct psGfx *ps, double x, double y); /* Move PostScript position to given point. */ void psTextAt(struct psGfx *ps, double x, double y, char *text); /* Output text in current font at given position. */ void psTextBox(struct psGfx *ps, double x, double y, char *text); /* Fill a box the size of the text at the given position*/ void psTextDown(struct psGfx *ps, double x, double y, char *text); /* Output text going downwards rather than across at position. */ void psTextRight(struct psGfx *mg, double x, double y, double width, double height, char *text); /* Draw a line of text right justified in box defined by x/y/width/height */ void psTextCentered(struct psGfx *mg, double x, double y, double width, double height, char *text); /* Draw a line of text centered in box defined by x/y/width/height */ void psTimesFont(struct psGfx *ps, double size); /* Set font to times of a certain size. */ void psSetColor(struct psGfx *ps, int r, int g, int b); /* Set current color. r/g/b values are between 0 and 255. */ void psSetGray(struct psGfx *ps, double grayVal); /* Set gray value (between 0.0 and 1.0. */ void psPushG(struct psGfx *ps); /* Save graphics state on stack. */ void psPopG(struct psGfx *ps); /* Pop off saved graphics state. */ void psDrawPoly(struct psGfx *ps, struct psPoly *poly, boolean filled); /* Draw a possibly filled polygon */ void psFillEllipse(struct psGfx *ps, double x, double y, double xrad, double yrad); /* Draw a filled ellipse */ void psDrawEllipse(struct psGfx *ps, double x, double y, double xrad, double yrad, double startAngle, double endAngle); /* Draw an ellipse outline */ void psDrawCurve(struct psGfx *ps, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4); /* Draw Bezier curve specified by 4 points: first (p1) and last (p4) * and 2 control points (p2, p3) */ void psSetDash(struct psGfx *ps, boolean on); /* Set dashed line mode on or off. If set on, show two points marked, with one point of space */ char * convertEpsToPdf(char *epsFile); /* Convert EPS to PDF and return filename, or NULL if failure. */ void psLineTo(struct psGfx *ps, double x, double y); /* Draw line from current point to given point, * and make given point new current point. */ void psCircle(struct psGfx *ps, double x, double y, double rad, boolean filled); #endif /* PSGFX_H */
C
/* #include<stdio.h> #include<stdlib.h> #include<conio.h> #define PASS 1 #define FAIL 0 void display_menu(); int check_PW(); void check_balance(); void deposit(); void withdraw(); int main() { int service; int balance = 0; printf("츮 ý 湮 ּż մϴ."); do { display_menu(); printf("ϴ 񽺸 ϼ."); scanf("%d", &service); switch (service) { case 1: check_balance(balance); break; case 2: deposit(balance); break; case 3: withdraw(balance); break; case 4: exit(0); } printf("\n 񽺸 Ͻø ƹŰ ."); _getch(); system("cls"); } while (service != 4); return 0; } void check_balance(int balance) { if (check_PW() == PASS) printf("\n ܾ : %d \n", balance); } void deposit(int balance) { int amount; printf("\n ԱϽ ݾ?"); scanf("%d", &amount); balance += amount; printf("\nԱ ܾ : %d \n", balance); } void withdraw(int balance) { int amount; if (check_PW() == PASS) { printf("Ͻ ݾ?"); scanf("%d", &amount); if (balance < amount) printf("\nܾ մϴ. ܾ %d \n", balance); else { balance -= amount; printf("\n ܾ : %d\n", balance); } } } int check_PW() { static int count = 0; int system_PW = 1111; int limit = 3; int input_PW; printf("\ný йȣ Էϼ"); scanf("%d", &input_PW); if (input_PW == system_PW) return PASS; else { count++; if (count == limit) { printf("йȣ 3ȸ ߻!\n"); printf("ź 񽺼͸ 湮ϼ.\n"); exit(0); } else { printf("йȣ ƲȽϴ. %dȸ !\n", count); return FAIL; } } } void display_menu(){ printf("\n\n"); printf("==================\n"); printf("== 1.ܾ ȸ ==\n"); printf("== 2.Ա ==\n"); printf("== 3. ==\n"); printf("== 4.׸ϱ ==\n"); printf("==================\n"); } */
C
#include <string.h> #include <stdio.h> #include <molerat/base.h> #include <molerat/queue.h> void queue_init(struct queue *q, unsigned int max_size) { q->capacity = 8; q->items = xalloc(q->capacity * sizeof *q->items); q->read = q->write = 0; q->max_size = max_size; wait_list_init(&q->waiters, 0); q->waiters_state = NEITHER; } void queue_fini(struct queue *q) { free(q->items); wait_list_fini(&q->waiters); } static void flip_waiters_state(struct queue *q, enum queue_waiters_state st) { if (q->waiters_state != st) { wait_list_set(&q->waiters, 0, TRUE); q->waiters_state = st; } } bool_t queue_push(struct queue *q, void *item, struct tasklet *t) { unsigned int size = q->write - q->read; if (size >= q->max_size) /* Queue full */ flip_waiters_state(q, WAS_FULL); if (q->waiters_state == WAS_FULL && !wait_list_down(&q->waiters, 1, t)) return 0; if (size == q->capacity) { /* items full. Resize. */ unsigned int capacity = q->capacity * 2; void **items = xalloc(capacity * sizeof *items); memcpy(items, q->items + q->read, (q->capacity - q->read) * sizeof *items); memcpy(items + q->capacity - q->read, q->items, (q->write - q->capacity) * sizeof *items); free(q->items); q->items = items; q->capacity = capacity; q->write -= q->read; q->read = 0; } q->items[q->write++ & (q->capacity - 1)] = item; if (q->waiters_state == WAS_EMPTY) wait_list_up(&q->waiters, 1); return 1; } void *queue_shift(struct queue *q, struct tasklet *t) { void *res; if (q->read == q->write) /* Queue empty */ flip_waiters_state(q, WAS_EMPTY); if (q->waiters_state == WAS_EMPTY && !wait_list_down(&q->waiters, 1, t)) return NULL; assert(q->read != q->write); res = q->items[q->read++]; if (q->read == q->capacity) { q->read = 0; q->write -= q->capacity; } if (q->waiters_state == WAS_FULL) wait_list_up(&q->waiters, 1); return res; }
C
#include "skynet.h" #include "skynet_module.h" #include "spinlock.h" #include <assert.h> #include <string.h> #include <dlfcn.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #define MAX_MODULE_TYPE 32 struct modules { int count; struct spinlock lock; const char * path; struct skynet_module m[MAX_MODULE_TYPE]; }; static struct modules * M = NULL; static void * _try_open(struct modules *m, const char * name) { const char *l; // default path is "./cservice/?.so" const char * path = m->path; size_t path_size = strlen(path); size_t name_size = strlen(name); int sz = path_size + name_size; //search path void * dl = NULL; char tmp[sz]; do { memset(tmp,0,sz); while (*path == ';') path++; if (*path == '\0') break; // current is first non-';' char // find the position of next ';', // if it is not found consider the end of the string as this position l = strchr(path, ';'); if (l == NULL) l = path + strlen(path); // copy the module name to replace the '?' in the path int len = l - path; int i; for (i=0;path[i]!='?' && i < len ;i++) { tmp[i] = path[i]; } memcpy(tmp+i,name,name_size); if (path[i] == '?') { strncpy(tmp+i+name_size,path+i+1,len - i - 1); } else { fprintf(stderr,"Invalid C service path\n"); exit(1); } // <dlfcn.h> void* dlopen(const char* filename, int flag); // 1. loads the dynamic library file named by the null-terminated string `filename` // and return an opaque "handle" for the dynamic library. // 2. if `filename` is NULL, then the returned handle is for the main program. // 3. if the library has dependencies on other shared libraries, // then these are also automatically loaded by the dynamic linker using the same rules. // 4. RTLD_NOW: all undefined symbols in the library are resolved before dlopen returns // 5. RTLD_GLOBAL: the symbols defined by this library will be available for // symbol resolution of subsequently loaded libraries. // load dynamic library file for example "./cservice/name.so" // and return the handle, if dynamic library loaded success then end the loop dl = dlopen(tmp, RTLD_NOW | RTLD_GLOBAL); path = l; }while(dl == NULL); if (dl == NULL) { fprintf(stderr, "try open %s failed : %s\n",name,dlerror()); } return dl; } static struct skynet_module * _query(const char * name) { int i; for (i=0;i<M->count;i++) { if (strcmp(M->m[i].name,name)==0) { return &M->m[i]; } } return NULL; } static int _open_sym(struct skynet_module *mod) { size_t name_size = strlen(mod->name); char tmp[name_size + 9]; // create/init/release/signal , longest name is release (7) memcpy(tmp, mod->name, name_size); strcpy(tmp+name_size, "_create"); mod->create = dlsym(mod->module, tmp); strcpy(tmp+name_size, "_init"); mod->init = dlsym(mod->module, tmp); strcpy(tmp+name_size, "_release"); mod->release = dlsym(mod->module, tmp); strcpy(tmp+name_size, "_signal"); mod->signal = dlsym(mod->module, tmp); return mod->init == NULL; } struct skynet_module * skynet_module_query(const char * name) { // query skynet module from M->m[i] by compare M->m[i].name with name // if found return this skynet module struct skynet_module * result = _query(name); if (result) return result; SPIN_LOCK(M) result = _query(name); // double check // if the module (such as "logger" and "snlua") is not found, // then load dynamic library and append new module to M and return this new module if (result == NULL && M->count < MAX_MODULE_TYPE) { int index = M->count; // try to load dymaic library of c service // located in "./cservice/<name>.so" (default setting) void * dl = _try_open(M,name); if (dl) { // if dynamic library load success, then: // 1. load synbols (<name>_create _init _release _signal) to M->m[index] // 2. M->m[index].name keep the name of module // 3. M->m[index].module keep the dynamic library handle // 4. add up the total moudle count // 5. return the new module M->m[index].name = name; M->m[index].module = dl; if (_open_sym(&M->m[index]) == 0) { M->m[index].name = skynet_strdup(name); M->count ++; result = &M->m[index]; } } } SPIN_UNLOCK(M) return result; } void skynet_module_insert(struct skynet_module *mod) { SPIN_LOCK(M) struct skynet_module * m = _query(mod->name); assert(m == NULL && M->count < MAX_MODULE_TYPE); int index = M->count; M->m[index] = *mod; ++M->count; SPIN_UNLOCK(M) } void * skynet_module_instance_create(struct skynet_module *m) { if (m->create) { return m->create(); } else { return (void *)(intptr_t)(~0); } } int skynet_module_instance_init(struct skynet_module *m, void * inst, struct skynet_context *ctx, const char * parm) { return m->init(inst, ctx, parm); } void skynet_module_instance_release(struct skynet_module *m, void *inst) { if (m->release) { m->release(inst); } } void skynet_module_instance_signal(struct skynet_module *m, void *inst, int signal) { if (m->signal) { m->signal(inst, signal); } } void skynet_module_init(const char *path) { struct modules *m = skynet_malloc(sizeof(*m)); m->count = 0; m->path = skynet_strdup(path); SPIN_INIT(m) M = m; }
C
/*5.5m ~n ֮*/ #include<stdio.h> int main(void) { int m,n,i; int factorsum(int t); printf("Input m: ");scanf("%d",&m); printf("Input n: ");scanf("%d",&n); for(i=m;i<=n;i++) { if(i==factorsum(i)) printf("%5d",i); } return 0; } /*tӺ*/ int factorsum(int t) { int sum=0,i; if(t==1) sum=1; for(i=1;i<t;i++) { if(t%i==0) sum=sum+i; } return sum; }
C
#include <ctype.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define ARG_LENGTH_MIN 2 #define ARG_LENGTH_MAX 6 typedef void (*sig_handler_t)(int); static void exit_sig_handler(int sig) { (void)sig; exit(EXIT_SUCCESS); } static void print_usage(char *exec_path) { char *exec_name = strrchr(exec_path, '/'); if (!exec_name) exec_name = exec_path; else ++exec_name; fprintf(stderr, "Usage: \n\ \n\ %s [options] [signal...]\n\ \n\ Waits for the specified signals before exiting. If a signal is not\n\ specified, it will be ignored.\n\ \n\ Supported signals:\n\ \n\ hup Hang-up signal.\n\ int Interrupt signal.\n\ pipe Broken pipe signal.\n\ term Termination signal.\n\ usr1 User-defined signal 1.\n\ usr2 User-defined signal 2.\n\ \n\ Available options:\n\ \n\ -?, -h, --help Display this help text and exit.\n\ ", exec_name); } static void print_invalid_argument(char *exec_path, char *arg) { if (*arg == '-') fprintf(stderr, "Invalid option: %s\n\n", arg); else fprintf(stderr, "Invalid signal: %s\n\n", arg); print_usage(exec_path); } int main(int argc, char **argv) { // Parse the signal handlers. sig_handler_t sigterm_handler = SIG_IGN; sig_handler_t sigint_handler = SIG_IGN; sig_handler_t sighup_handler = SIG_IGN; sig_handler_t sigpipe_handler = SIG_IGN; sig_handler_t sigusr1_handler = SIG_IGN; sig_handler_t sigusr2_handler = SIG_IGN; char arg_lower[ARG_LENGTH_MAX + 1]; for (int argi = 1; argi < argc; ++argi) { char *arg = argv[argi]; size_t arg_len = strlen(arg); if ((arg_len < ARG_LENGTH_MIN) || (arg_len > ARG_LENGTH_MAX)) { print_invalid_argument(argv[0], arg); return EXIT_FAILURE; } // Convert the argument to lower case. char *arg_pos = arg; char *arg_lower_pos = arg_lower; char pos; while ((pos = *arg_pos++)) *arg_lower_pos++ = tolower(pos); *arg_lower_pos = 0; // Parse the argument. if ((strcmp(arg_lower, "-h") == 0) || (strcmp(arg_lower, "-?") == 0) || (strcmp(arg_lower, "--help") == 0)) { print_usage(argv[0]); return EXIT_FAILURE; } else if (strcmp(arg_lower, "term") == 0) sigterm_handler = exit_sig_handler; else if (strcmp(arg_lower, "int") == 0) sigint_handler = exit_sig_handler; else if (strcmp(arg_lower, "hup") == 0) sighup_handler = exit_sig_handler; else if (strcmp(arg_lower, "pipe") == 0) sigpipe_handler = exit_sig_handler; else if (strcmp(arg_lower, "usr1") == 0) sigusr1_handler = exit_sig_handler; else if (strcmp(arg_lower, "usr2") == 0) sigusr2_handler = exit_sig_handler; else { print_invalid_argument(argv[0], arg); return EXIT_FAILURE; } } // Set up the signal handlers. sig_handler_t old_handler; #define SET_UP_SIGNAL_HANDLER(_signal, _handler) \ if ((old_handler = signal(_signal, _handler)) == SIG_ERR) \ { \ fprintf(stderr, "Failed to set signal handler " #_signal); \ return EXIT_FAILURE; \ } SET_UP_SIGNAL_HANDLER(SIGTERM, sigterm_handler) SET_UP_SIGNAL_HANDLER(SIGINT, sigint_handler) SET_UP_SIGNAL_HANDLER(SIGHUP, sighup_handler) SET_UP_SIGNAL_HANDLER(SIGPIPE, sigpipe_handler) SET_UP_SIGNAL_HANDLER(SIGUSR1, sigusr1_handler) SET_UP_SIGNAL_HANDLER(SIGUSR2, sigusr2_handler) #undef SET_UP_SIGNAL_HANDLER // Sleep indefinitely. while (1) sleep(3600); return EXIT_SUCCESS; }
C
#include <stdio.h> int main (void) { int rows; int number; char t[1000]; char c; scanf("%d",&rows); getchar(); while (rows--) { while(fgets(t,1000,stdin) != NULL) { //printf("%s",t); //printf("%c",t[2]); scanf("%d",&number); getchar(); t[number] = '\0'; printf("%s",t); printf("\n"); } } return 0; }
C
/**********************************************/ rational * rational_assign(rational * data, rational * y) { integer_destroy(data->num); integer_destroy(data->den); data->num = integer_copy(y->num); data->den = integer_copy(y->den); rational_normalize(data); return data; }
C
#include "winctl.h" #include "taskbar.h" #include <stdlib.h> static bool winctl_left_btn_handler(xtk_spirit_t *spirit, void *arg) { winctl_t *winctl = (winctl_t *) arg; if (!winctl) { return false; } uview_msg_t msg; if (winctl == taskbar.last_winctl) { /* 隐藏/显示 */ if (winctl->ishidden) { /* 是一个隐藏的窗口,就显示 */ uview_msg_header(&msg, UVIEW_MSG_SHOW, winctl->winid); uview_send_msg(taskbar.spirit->view, &msg); } else { /* 已经是聚焦的窗口,那么再次点击就隐藏 */ uview_msg_header(&msg, UVIEW_MSG_HIDE, winctl->winid); uview_send_msg(taskbar.spirit->view, &msg); } } else { /* 不是最新的窗口控制,就显示 */ uview_msg_header(&msg, UVIEW_MSG_SHOW, winctl->winid); uview_send_msg(taskbar.spirit->view, &msg); } return true; } winctl_t *winctl_create(int winid) { if (winid < 0) return NULL; winctl_t *winctl = malloc(sizeof(winctl_t)); if (winctl == NULL) return NULL; winctl->button = xtk_button_create(); if (!winctl->button) { free(winctl); return NULL; } winctl->winid = winid; winctl->ishidden = false; /* 默认是显示 */ winctl->isfocus = false; /* 默认不聚焦 */ winctl->button->style.border_color = XTK_NONE_COLOR; winctl->button->style.background_color = taskbar.winctl_back_color; xtk_button_t *btn = XTK_BUTTON(winctl->button); btn->color_idle = taskbar.winctl_back_color; btn->color_touch = XTK_RGB_ADD(taskbar.winctl_back_color, 0x40, 0x40, 0x40); btn->color_click = XTK_RGB_ADD(taskbar.winctl_back_color, 0x20, 0x20, 0x20); xtk_spirit_set_size(winctl->button, WINCTL_SIZE_DEFAULT, WINCTL_SIZE_DEFAULT); // 点击事件 xtk_signal_connect(winctl->button, "button_press", winctl_left_btn_handler, winctl); list_add_tail(&winctl->list, &taskbar.winctl_list_head); xtk_container_add(XTK_CONTAINER(taskbar.spirit), winctl->button); return winctl; } int winctl_destroy(winctl_t *winctl) { if (!winctl) return -1; xtk_container_remove(XTK_CONTAINER(taskbar.spirit), winctl->button); list_del(&winctl->list); if (xtk_spirit_destroy(winctl->button) < 0) return -1; free(winctl); return 0; } int winctl_destroy_all() { winctl_t *winctl, *winctl_next; list_for_each_owner_safe (winctl, winctl_next, &taskbar.winctl_list_head, list) { winctl_destroy(winctl); } return 0; } winctl_t *winctl_find(int winid) { winctl_t *winctl; list_for_each_owner (winctl, &taskbar.winctl_list_head, list) { if (winctl->winid == winid) return winctl; } return NULL; } void winctl_get_focus(winctl_t *winctl) { taskbar.last_winctl = winctl; winctl->isfocus = true; xtk_button_t *btn = XTK_BUTTON(winctl->button); btn->color_idle = taskbar.winctl_active_color; btn->spirit.style.background_color = btn->color_idle; } void winctl_lost_focus(winctl_t *winctl) { winctl->isfocus = false; xtk_button_t *btn = XTK_BUTTON(winctl->button); btn->color_idle = taskbar.winctl_back_color; btn->spirit.style.background_color = btn->color_idle; } int winctl_set_icon(winctl_t *winctl, char *pathname) { if (!winctl || !pathname) return -1; xtk_spirit_t *spirit = winctl->button; if (!spirit) return -1; /* 如果设置图标失败则尝试用默认图标 */ if (xtk_spirit_set_image2(spirit, pathname, WINCTL_ICON_SIZE, WINCTL_ICON_SIZE) < 0) if (xtk_spirit_set_image2(spirit, WINCTL_ICON_PATH_DEFAULT, WINCTL_ICON_SIZE, WINCTL_ICON_SIZE) < 0) return -1; xtk_spirit_show(spirit); return 0; } /** * 当窗口控制为NULL时,则重绘整个窗口控制 * 不然就绘制指定的窗口控制 */ void winctl_paint(winctl_t *winctl) { if (winctl) { xtk_spirit_show(winctl->button); } else { /* 先刷新背景,再显示 */ taskbar_draw_back(); int x = 4, y = 4; winctl_t *tmp; list_for_each_owner (tmp, &taskbar.winctl_list_head, list) { xtk_spirit_set_pos(tmp->button, x, y); /* 调整位置 */ xtk_spirit_show(tmp->button); x += WINCTL_ICON_SIZE + 4 + 2; /* 显示到最低端就不显示 */ if (x >= taskbar.screen_width - WINCTL_ICON_SIZE - 4) break; } } }
C
#include "render.h" #include "scene.h" #include "intersection.h" #include "maths.h" #include "config.h" #include "utils.h" #include "queue.h" #include "photon.h" #include <stdio.h> #include <pthread.h> #include <stdlib.h> struct thread_input_data { int x; int y; bool last; }; struct thread_output_data { int x; int y; uint32_t rgb; }; static queue_t *g_input_queue; static queue_t *g_output_queue; static scene_t *scene; static void process_initial_ray(scene_t *scene, ray_t *ray, double *colour_out) { intersection_t info; ray->depth = 0; if(intersection_ray_scene(ray, scene, &info)) { colour_out[0] += info.scene.colour[0]; colour_out[1] += info.scene.colour[1]; colour_out[2] += info.scene.colour[2]; } else { vector_copy(scene->sky, colour_out); } } void *renderer(void *data) { struct thread_input_data input; ray_t ray; queue_read(g_input_queue, &input); while(!input.last) { double colour[3] = {0, 0, 0}; int n = g_config.samples; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { camera_create_initial_ray(scene->camera, input.x, input.y, i, j, &ray); process_initial_ray(scene, &ray, colour); } } vector_div(n * n, colour, colour); uint32_t pixdata = convert_double_rgb_to_24bit(colour); struct thread_output_data out = {.x = input.x, .y = input.y, .rgb = pixdata}; queue_write(g_output_queue, &out); queue_read(g_input_queue, &input); } return NULL; } void start_threads(pthread_t *threads) { for(int i = 0; i < g_config.num_threads; i++) { pthread_create(threads + i, NULL, renderer, NULL); } } void *feed_pixels(void *_data) { struct thread_input_data data; for(int i = 0; i < g_config.height; i++) { for(int j = 0; j < g_config.width; j++) { data.x = j; data.y = i; data.last = false; queue_write(g_input_queue, &data); } } //Tell the threads that we are done. for(int i = 0; i < g_config.num_threads; i++) { data.last = true; queue_write(g_input_queue, &data); } return NULL; } pthread_t start_feed_thread(void) { pthread_t thread; pthread_create(&thread, NULL, feed_pixels, NULL); return thread; } void trace_pixel(void) { double colour_out[] = {0,0,0}; ray_t ray; camera_create_initial_ray(scene->camera, g_config.trace_pixel_x, g_config.trace_pixel_y, 0, 0, &ray); process_initial_ray(scene, &ray, colour_out); vector_print(colour_out); } void render(scene_t *scene_in) { int width = g_config.width; int height = g_config.height; scene = scene_in; int start_time = time(NULL); #if PMAP photon_map_build(scene, g_config.photons); #endif VERBOSE("Rendering.\n"); if(g_config.trace_pixel) { trace_pixel(); } else { pthread_t *threads = calloc(sizeof(pthread_t) * g_config.num_threads, 1); g_input_queue = queue_init(1000, sizeof(struct thread_input_data)); g_output_queue = queue_init(1000, sizeof(struct thread_output_data)); start_threads(threads); pthread_t feed_thread = start_feed_thread(); struct thread_output_data output; for(int i = 0; i < height; i++) { progress_bar(i, height, 40); for(int j = 0; j < width; j++) { queue_read(g_output_queue, &output); scene_update_pixel(scene, output.x, output.y, output.rgb); } } progress_bar(1, 1, 40); VERBOSE("Render took %d seconds.\n", time(0) - start_time); //Wait for the threads to finish. pthread_join(feed_thread, NULL); for(int i = 0; i < g_config.num_threads; i++) { pthread_join(threads[i], NULL); } free(threads); queue_delete(g_input_queue); queue_delete(g_output_queue); } }
C
/* * Copyright (C) 2013-2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <printf.h> #include <stdio.h> #include <string.h> #include <trusty_std.h> #include <err.h> #define LINE_BUFFER_SIZE 128 struct file_buffer { char data[LINE_BUFFER_SIZE]; size_t pos; }; struct file_context { int fd; struct file_buffer *buffer; }; struct file_buffer stdout_buffer = {.pos = 0}; struct file_buffer stderr_buffer = {.pos = 0}; struct file_context fctx[3] = { {.fd = 0, .buffer = NULL}, {.fd = 1, .buffer = &stdout_buffer }, {.fd = 2, .buffer = &stderr_buffer } }; static int buffered_put(struct file_buffer *buffer, int fd, char c) { int result = 0; buffer->data[buffer->pos++] = c; if (buffer->pos == sizeof(buffer->data) || c == '\n') { result = write(fd, buffer->data, buffer->pos); buffer->pos = 0; } return result; } static int buffered_write(struct file_context *ctx, const char *str, size_t sz) { unsigned i; if (!ctx->buffer) { return ERR_INVALID_ARGS; } for (i = 0; i < sz; i++) { int result = buffered_put(ctx->buffer, ctx->fd, str[i]); if (result < 0) { return result; } } return sz; } static ssize_t __stdin_write(io_handle_t *io, const char *s, size_t len) { return buffered_write(&fctx[0], s, len); } static ssize_t __stdout_write(io_handle_t *io, const char *s, size_t len) { return buffered_write(&fctx[1], s, len); } static ssize_t __stderr_write(io_handle_t *io, const char *s, size_t len) { return buffered_write(&fctx[2], s, len); } static ssize_t __null_read(io_handle_t *io, char *s, size_t len) { return (unsigned char)0xff; } static const io_handle_hooks_t stdin_io_hooks = { .write = __stdin_write, .read = __null_read, }; static const io_handle_hooks_t stdout_io_hooks = { .write = __stdout_write, .read = __null_read, }; static const io_handle_hooks_t stderr_io_hooks = { .write = __stderr_write, .read = __null_read, }; io_handle_t stdin_io = IO_HANDLE_INITIAL_VALUE(&stdin_io_hooks); io_handle_t stdout_io = IO_HANDLE_INITIAL_VALUE(&stdout_io_hooks); io_handle_t stderr_io = IO_HANDLE_INITIAL_VALUE(&stderr_io_hooks); #define DEFINE_STDIO_DESC(id, handle) \ [(id)] = { \ .io = &handle, \ } FILE __stdio_FILEs[3] = { DEFINE_STDIO_DESC(0, stdin_io), /* stdin */ DEFINE_STDIO_DESC(1, stdout_io), /* stdout */ DEFINE_STDIO_DESC(2, stderr_io), /* stderr */ }; #undef DEFINE_STDIO_DESC
C
/* program that declares a variable n, forks a new process and prints “Hello from parent [PID - n]” and “Hello from child [PID - n]” from parent and child processes respectively. */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> void main(void) { pid_t n; int m = fork(); n = getpid(); if (m == 0) { printf("Hello from child [PID - %d]\n", n); } else { printf("Hello from parent [PID - %d]\n", n); } }
C
#include "ft_includes.h" void ft_error(void) { ft_putstr("Error\n"); } int main(int argc, char **argv) { char **res; int *tab_possibility; int **arr; tab_possibility = NULL; if (argc == 2) res = ft_split(argv[1]); arr = ft_tab_init(); if (argc != 2 || ft_check_error(argv[1]) == 0) ft_error(); else { ft_backtracking(arr, res, tab_possibility); if (ft_is_solvable(arr) == 0) ft_error(); else ft_print_tab(arr); ft_free_tab(arr, res); } return (0); }
C
/* * maps.h * * Created on: 08.05.2018. * Author: student */ #include<stdbool.h> #ifndef MAPS_H_ #define MAPS_H_ #define SIZEROW 15 #define SIZECOLUMN 20 struct Level { unsigned char initial_map[SIZEROW][SIZECOLUMN]; int start_row; int start_column; }; // Map 1 struct Level level1 = { .initial_map = { {'G','G','D','G','G','G','G','G','G','G','G','G','B','B','G','G','G','G','G','O'}, {'G','G','D','G','G','G','G','G','G','G','G','G','B','B','1','2','3','G','G','t'}, {'G','G','D','G','G','G','D','D','D','G','G','G','G','G','4','5','6','G','G','G'}, {'G','G','D','G','G','G','D','S','D','G','G','G','G','G','G','G','G','G','G','G'}, {'G','G','D','G','G','G','D','G','D','G','G','G','G','G','G','G','G','G','G','G'}, {'G','G','D','X','G','S','D','G','D','G','G','G','G','G','G','G','G','S','G','7'}, {'G','G','D','D','D','D','D','G','D','G','G','G','G','D','D','D','D','D','D','D'}, {'G','G','G','G','G','G','G','G','D','G','G','G','G','D','S','G','G','G','G','7'}, {'G','G','G','G','G','G','G','G','D','G','G','G','G','D','G','G','G','G','G','G'}, {'G','B','G','G','G','G','G','G','D','G','G','G','G','D','G','G','B','G','G','G'}, {'B','G','B','B','G','G','G','G','D','S','G','G','S','D','G','G','G','G','B','G'}, {'B','G','G','B','B','G','B','G','D','D','D','D','D','D','G','G','G','G','G','B'}, {'G','B','B','G','G','G','G','G','G','G','G','G','G','G','G','G','G','B','B','B'}, {'G','G','B','B','B','G','G','G','G','G','G','G','G','G','B','G','B','B','G','B'}, {'B','B','G','B','G','G','G','B','B','B','G','B','G','G','G','B','G','B','B','G'}, }, .start_row = 0, .start_column = 2}; struct Level level2 = { .initial_map = { {'G','B','B','B','B','B','B','G','B','G','G','G','G','B','B','G','G','G','G','O'}, {'G','G','G','B','B','B','B','B','G','B','G','G','B','B','G','G','G','B','G','t'}, {'B','G','G','B','B','B','G','G','G','G','B','B','B','G','G','B','B','G','S','7'}, {'B','B','B','B','G','B','G','G','B','B','B','B','B','D','D','D','D','D','D','D'}, {'G','G','B','G','G','B','G','G','B','B','B','B','B','D','S','B','G','B','B','7'}, {'G','B','B','B','B','G','B','B','S','B','B','B','S','D','G','G','G','B','B','B'}, {'B','B','B','B','D','D','D','D','D','D','D','D','D','D','B','B','B','B','B','B'}, {'B','G','G','G','D','S','G','G','G','G','G','B','B','G','B','B','G','G','B','B'}, {'B','B','B','B','D','B','G','B','B','B','B','B','B','G','G','G','B','B','B','B'}, {'B','B','B','B','D','D','D','B','G','G','B','B','B','B','B','B','B','B','G','B'}, {'B','B','X','B','B','S','D','B','G','B','B','B','B','B','B','B','G','B','B','B'}, {'D','D','D','D','D','D','D','B','B','B','B','G','B','B','B','G','G','B','B','B'}, {'G','G','B','B','S','B','G','B','B','B','G','B','B','B','B','B','G','G','G','G'}, {'G','G','G','B','B','B','B','B','G','B','B','G','B','B','G','B','G','1','2','3'}, {'G','G','G','B','B','B','B','B','B','B','B','B','B','G','B','B','B','4','5','6'}, }, .start_row = 11, .start_column = 0}; struct Level level3 = { .initial_map = { {'G','G','B','B','G','G','G','D','B','B','b','G','G','G','B','G','G','G','G','G'}, {'G','G','B','B','G','G','G','D','B','B','R','B','B','B','B','B','B','B','B','B'}, {'G','G','G','G','G','G','X','D','G','G','r','N','N','N','N','N','N','N','N','N'}, {'B','B','G','G','D','D','D','D','G','G','G','G','S','G','G','G','G','G','G','B'}, {'G','B','G','G','D','B','B','G','B','D','D','D','D','D','D','D','D','G','G','B'}, {'G','B','G','S','D','B','B','B','B','D','S','B','G','G','G','S','D','G','G','B'}, {'B','B','D','D','D','B','B','B','B','D','D','B','B','G','B','B','D','D','G','B'}, {'B','G','D','G','B','1','2','3','G','G','D','G','B','B','B','B','B','D','B','B'}, {'B','S','D','G','B','4','5','6','G','G','D','G','G','B','B','B','B','D','B','B'}, {'B','B','D','G','B','B','B','B','B','B','D','S','G','B','G','B','B','D','G','G'}, {'B','B','D','G','S','B','B','B','G','B','D','G','G','B','G','B','B','D','S','7'}, {'B','B','D','D','D','D','D','D','B','B','D','G','G','B','G','G','G','D','D','D'}, {'G','B','G','G','G','G','G','D','S','B','D','G','G','B','B','G','G','G','G','7'}, {'G','B','B','B','G','G','G','D','D','D','D','G','G','G','B','B','B','B','B','G'}, {'G','G','G','B','B','B','B','B','G','G','G','G','G','G','B','G','G','B','B','G'}, }, .start_row = 0, .start_column = 7}; // game Over unsigned char gameOver[SIZEROW][SIZECOLUMN] = { {'D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D'}, {'D',0,0,0,0,'D',0,0,0,'D',0,'D','D','D',0,'D',0,0,0,'D'}, {'D',0,'D','D',0,'D',0,'D',0,'D',0,0,'D',0,0,'D',0,'D','D','D'}, {'D',0,'D','D','D','D',0,'D',0,'D',0,'D',0,'D',0,'D',0,'D','D','D'}, {'D',0,'D',0,0,'D',0,0,0,'D',0,'D',0,'D',0,'D',0,0,'D','D'}, {'D',0,'D','D',0,'D',0,'D',0,'D',0,'D','D','D',0,'D',0,'D','D','D'}, {'D',0,0,0,0,'D',0,'D',0,'D',0,'D','D','D',0,'D',0,0,0,'D'}, {'D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D'}, {'D','D',0,0,0,0,'D',0,'D',0,'D',0,0,0,'D',0,0,0,'D','D'}, {'D','D',0,'D','D',0,'D',0,'D',0,'D',0,'D','D','D',0,'D',0,'D','D'}, {'D','D',0,'D','D',0,'D',0,'D',0,'D',0,'D','D','D',0,'D',0,'D','D'}, {'D','D',0,'D','D',0,'D',0,'D',0,'D',0,0,'D','D',0,0,0,'D','D'}, {'D','D',0,'D','D',0,'D',0,'D',0,'D',0,'D','D','D',0,0,'D','D','D'}, {'D','D',0,0,0,0,'D','D',0,'D','D',0,0,0,'D',0,'D',0,'D','D'}, {'D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D'}, }; // lvl complete unsigned char nextLvl[SIZEROW][SIZECOLUMN] = { {'G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G'}, {'G','G',0,'G','G',0,'G',0,0,0,'G',0,'G',0,'G',0,0,0,'G','G'}, {'G','G',0,0,'G',0,'G',0,'G','G','G','G',0,'G','G','G',0,'G','G','G'}, {'G','G',0,'G',0,0,'G',0,0,0,'G','G',0,'G','G','G',0,'G','G','G'}, {'G','G',0,'G','G',0,'G',0,'G','G','G','G',0,'G','G','G',0,'G','G','G'}, {'G','G',0,'G','G',0,'G',0,0,0,'G',0,'G',0,'G','G',0,'G','G','G'}, {'G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G'}, {'G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G'}, {'G','G','G','G',0,'G','G','G',0,'G',0,'G','G',0,'G','G','G','G','G','G'}, {'G','G','G','G',0,'G','G','G',0,'G',0,'G','G',0,'G','G','G','G','G','G'}, {'G','G','G','G',0,'G','G','G',0,'G',0,'G','G',0,'G','G','G','G','G','G'}, {'G','G','G','G',0,'G','G','G',0,'G',0,'G','G',0,'G','G','G','G','G','G'}, {'G','G','G','G',0,'G','G','G',0,'G',0,'G','G',0,'G','G','G','G','G','G'}, {'G','G','G','G',0,0,0,'G','G',0,'G','G','G',0,0,0,'G','G','G','G'}, {'G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G','G'}, }; // You won unsigned char youWon[SIZEROW][SIZECOLUMN]= { {'D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D'}, {'D','D',0,'D','D','D',0,'D',0,0,0,0,0,'D',0,'D','D',0,'D','D'}, {'D','D','D',0,'D',0,'D','D',0,'D','D','D',0,'D',0,'D','D',0,'D','D'}, {'D','D','D','D',0,'D','D','D',0,'D','D','D',0,'D',0,'D','D',0,'D','D'}, {'D','D','D','D',0,'D','D','D',0,'D','D','D',0,'D',0,'D','D',0,'D','D'}, {'D','D','D','D',0,'D','D','D',0,'D','D','D',0,'D',0,'D','D',0,'D','D'}, {'D','D','D','D',0,'D','D','D',0,0,0,0,0,'D',0,0,0,0,'D','D'}, {'D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D'}, {'D','D',0,'D','D','D',0,'D',0,0,0,0,0,'D',0,'D','D',0,'D','D'}, {'D','D',0,'D','D','D',0,'D',0,'D','D','D',0,'D',0,0,'D',0,'D','D'}, {'D','D',0,'D',0,'D',0,'D',0,'D','D','D',0,'D',0,0,'D',0,'D','D'}, {'D','D',0,'D',0,'D',0,'D',0,'D','D','D',0,'D',0,'D',0,0,'D','D'}, {'D','D',0,0,'D',0,0,'D',0,'D','D','D',0,'D',0,'D',0,0,'D','D'}, {'D','D',0,'D','D','D',0,'D',0,0,0,0,0,'D',0,'D','D',0,'D','D'}, {'D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D','D'}, }; bool mapChanges[SIZEROW][SIZECOLUMN]={ {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true}, }; #endif /* MAPS_H_ */