language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> int main() { // read only char file1 = open("foo.txt", O_RDONLY); //read & write char file2 = open("outfoo.txt", O_RDWR); //reads from file printf("Reading! \n"); char info[9]; if(read(file1, info, 9) < 0){ printf("reading error"); } printf("Writing! \n"); if (write(file2, info , 9) != 9){ printf("writing error"); } printf("Terminated"); close(file1); close(file2); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define MAX_EVENTS 5 #define MAX_BUF 32 //here comes global variables // int g_server_port = 2777; int epfd = 0; /** * set nonblocking file descriptor * */ int setnonblocking(int sock) { int opts = fcntl(sock,F_GETFL); if( opts<0 ){ perror("fcntl(sock, GETFL) error!"); return -1; } opts = opts | O_NONBLOCK; if( fcntl(sock, F_SETFL, opts)<0 ){ perror("fcntl(sock,SETFL,opts) error!"); return -1; } return 0; } /** * init epoll instance * return value: * 0 - success * other - failed */ int init_epoll() { int ret = 0; epfd = epoll_create(MAX_EVENTS); if( epfd == -1 ){ perror("epoll created error!"); ret = -1; } return ret; } int handle_accept(int fd) { struct epoll_event ev; int newsock = accept(fd,NULL,NULL); if( newsock == -1 ){ perror("accept error"); return -1; } printf("Client accept with descriptor #%d \n" ,newsock); setnonblocking(newsock); //set nonblocking ev.data.fd = newsock; ev.events = EPOLLIN; if( -1 == epoll_ctl(epfd, EPOLL_CTL_ADD, newsock, &ev) ){ perror("epoll_ctl error!"); return -1; } return 0; } int handle_read(int fd) { int nread = 0; char buf[MAX_BUF+1] = {0}; struct epoll_event ev; nread = recv(fd, buf, MAX_BUF, 0); if( nread <=0 ){ close(fd); //epoll_ctl(epfd, EPOLL_CTL_DEL,fd,NULL); //close will automatically remove it from epoll instance! printf("can not read more! "); } else { buf[nread] = '\0'; printf("%s \n",buf); //prepare to write! ev.data.fd = fd; ev.events = EPOLLOUT; if( -1 == epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &ev)){ perror("epoll_ctl ctl_mod error"); return -1; } } return 0; } int handle_write(int fd) { int nwrite = 0; char buf[MAX_BUF+1] = {0}; snprintf(buf, MAX_BUF,"hello, client #%i",fd); nwrite = send(fd, buf, sizeof(buf), 0); return 0; } int main(int argc, const char* argv[]) { struct sockaddr_in sAddr; struct epoll_event ev; struct epoll_event evlist[MAX_EVENTS]; int ready, i; int listensock = 0; int result=0, val = 0; //init epoll if( init_epoll() ){ exit(-1); } printf("epoll instance created success! \n"); //create socket if ( -1 == (listensock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("create socket error!"); exit(1); } val = 1; result = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &val,sizeof(val)); if( result < 0 ){ perror("set socket option error!"); exit(1); } sAddr.sin_family = AF_INET; sAddr.sin_port = htons(g_server_port); sAddr.sin_addr.s_addr = INADDR_ANY; //now bind the address and port result = bind(listensock, (struct sockaddr*)&sAddr, sizeof(sAddr)); if ( result < 0 ) { perror("bind error!"); exit(1); } //print server ready info printf("Server get ready at port : %d \n", g_server_port); result = listen(listensock, 5); if( result < 0 ) { perror("listen error!"); exit(1); } setnonblocking(listensock); //set nonblocking! ev.events = EPOLLIN; ev.data.fd = listensock; if( epoll_ctl(epfd, EPOLL_CTL_ADD, listensock, &ev) == -1 ){ perror("epoll_ctl add error!"); exit(-1); } //now we will epoll_wait the event // while(1) { //Fetch up to MAX_EVENTS items from the ready list //printf("About to epoll_wait() \n"); ready = epoll_wait(epfd, evlist, MAX_EVENTS, -1); if( ready == -1 ){ if( errno == EINTR ){ printf("Get a intr signal!\n"); continue; } else { perror("epoll_wait error!"); exit(-1); } } for(i=0;i<ready;i++){ /* printf("fd=%d, events: %s%s%s%s \n",evlist[i].data.fd, (evlist[i].events & EPOLLIN)? "EPOLLIN ":"", (evlist[i].events & EPOLLOUT)? "EPOLLOUT ":"", (evlist[i].events & EPOLLHUP)? "EPOLLHUP ":"", (evlist[i].events & EPOLLERR)? "EPOLLERR ":""); */ //deal with events if( evlist[i].events & EPOLLIN ){ if( evlist[i].data.fd == listensock ){ handle_accept(evlist[i].data.fd); } else { handle_read(evlist[i].data.fd); } } else if( evlist[i].events & EPOLLOUT){ handle_write(evlist[i].data.fd); } else if( evlist[i].events &(EPOLLHUP|EPOLLERR)){ printf("Client on descriptor #%d disconnetcted. \n", evlist[i].data.fd); if( close( evlist[i].data.fd ) == -1 ){ perror("close fd error!"); exit(-1); } } }//end of for ready }//end of while return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { float height, m, weight, BMI; printf("BMI\n"); printf("height(cm): "); scanf_s("%f", &height); printf("weight(kg): "); scanf_s("%f", &weight); m = height / 100; BMI = weight / (m*m); printf("BMI = %.1f\n\n", BMI); if (BMI < 18.5) printf("Undermeight\n\n"); if (BMI >= 18.5 && BMI < 24.9) printf("Normal\n\n"); if (BMI >= 25 && BMI < 29.9) printf("Overweight\n\n"); if (BMI >= 30) printf("Obese\n\n"); system("pause"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* read_map_textures.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adzikovs <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/23 12:42:56 by adzikovs #+# #+# */ /* Updated: 2018/11/24 12:09:55 by adzikovs ### ########.fr */ /* */ /* ************************************************************************** */ #include "common_typedefs.h" int rt_error_exit(t_saved_xpm_texture **res, t_saved_xpm_texture *last, t_xpm_color *last_colors, t_saved_xpm_texture *last_data) { size_t i; i = 0; while (res[i]) { if (res[i]->texture.data) free(res[i]->texture.data); if (res[i]->texture.colors) free(res[i]->texture.colors); free(res[i]); res[i] = NULL; i++; } if (last) free(last); if (last_data) free(last_data->texture.data); if (last_colors) free(last_colors); return (1); } int check_texture(t_xpm_texture *txt) { if (txt == NULL) return (1); if (txt->header.w <= 0 || txt->header.h <= 0 || txt->header.colors == 0 || txt->header.chars_per_pixel != 1) return (1); if (txt->x[0] != 0 || fabs(txt->x[1] + 1 - txt->header.w) > DBL_ZERO || txt->y[0] != 0 || fabs(txt->y[1] + 1 - txt->header.h) > DBL_ZERO) return (1); return (0); } int read_map_textures(int fd, t_saved_xpm_texture **res, size_t am) { t_saved_xpm_texture *tmp; size_t size; size_t i; i = 0; while (i < am) { tmp = (t_saved_xpm_texture*)malloc(sizeof(*tmp)); if (read(fd, tmp, sizeof(*tmp)) != sizeof(*tmp)) return (rt_error_exit(res, tmp, NULL, NULL)); if (check_texture(&tmp->texture)) return (rt_error_exit(res, tmp, NULL, NULL)); size = sizeof(*tmp->texture.colors) * tmp->texture.header.colors; tmp->texture.colors = (t_xpm_color*)malloc(size); if (read(fd, tmp->texture.colors, size) != (ssize_t)size) return (rt_error_exit(res, tmp, tmp->texture.colors, NULL)); size = (size_t)tmp->texture.header.w * tmp->texture.header.h + 1; tmp->texture.data = (char*)malloc(size); if (read(fd, tmp->texture.data, size) != (ssize_t)size) return (rt_error_exit(res, tmp, tmp->texture.colors, tmp)); res[i] = tmp; i++; } return (0); }
C
#include <stdio.h> #define INT_SIZE sizeof(int) * 8 /* Bits required to represent an integer */ int main() { int raqam, sanamoq, i; printf("Har qanday raqamni kiriting "); scanf("%d", &raqam); sanamoq = 0; for(i=0; i<INT_SIZE; i++) { if((raqam >> i ) & 1) { break; } sanamoq++; } printf("Total number of trailing zeros in %d is %d.", raqam, sanamoq); return 0; }
C
/* * [email protected] */ #include <stdio.h> double fatorial(double); double fatorial(double n) { double r = 1L; double f; for (f = 1; f <= n; f = f + 1L) r = r * f; return r; } int main() { double n; scanf("%lf", &n); double f = fatorial(n); printf("N=%f\nF=%f\n", n, f); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** 42sh ** File description: ** 42sh */ #include "../../../include/my.h" #include "../../../include/mysh.h" char *cpy_op(int i, char *str) { char *op = x_memset(0, my_strlen(str), sizeof(char)); int k = 0; if (!op) return (NULL); for (; str[i] != '\0' && str[i] != ')'; i += 1) { op[k] = str[i]; k += 1; } return (op); } char *get_if_var(char *str) { char *op = NULL; for (int i = 0; str[i] != '\0'; i += 1) { if (str[i] == '(') { i += 1; op = cpy_op(i, str); } } return (op); } int dif_op(char **shif, var_t **var) { if (dif_op_var(var, shif) == 1) return (1); if (var[0] == NULL && var[1] != NULL) { if (var[1]->k == 1 && my_str_isnum(shif[0]) == 1) { if (var[1]->value != my_getnbr(shif[0])) return (1); } if (var[1]->k == 0 && my_str_isnum(shif[0]) == 0) { if (my_strcmp(var[0]->data, shif[0]) == 1) return (1); } } if (var[0] == NULL && var[1] == NULL) { if (my_str_isnum(shif[0]) == 1 && my_str_isnum(shif[2]) == 1) { if (my_getnbr(shif[0]) != my_getnbr(shif[2])) return (1); } else if (my_strcmp(shif[0], shif[2]) != 0) return (1); } return (0); }
C
#include <conf.h> #include <kernel.h> #include <proc.h> #include <paging.h> pt_t* global_page_table[4]; /*------------------------------------------------------------------------- * initialize global page tables which will map 16MB physical memory *------------------------------------------------------------------------- */ SYSCALL init_global_pt() { STATWORD ps; int num_global_pt, num_entry_pt; pt_t* page_table; disable(ps); for( num_global_pt=0; num_global_pt<4; num_global_pt++) { page_table = create_a_page_table(0, FR_TBL); //null process initializes everything // kprintf("\n Gloabl PT %d and address is %d and page no is %d \n", num_global_pt, (unsigned int)page_table, ((unsigned int)page_table/NBPG)); if( page_table == NULL ) { restore(ps); return(SYSERR); } for( num_entry_pt=0; num_entry_pt<(NBPG/4); num_entry_pt++) { page_table[num_entry_pt].pt_pres = 1; /* page is present? */ page_table[num_entry_pt].pt_write = 1; /* page is writable? */ page_table[num_entry_pt].pt_user = 0; /* is use level protection? */ page_table[num_entry_pt].pt_pwt = 0; /* write through for this page? */ page_table[num_entry_pt].pt_pcd = 0; /* cache disable for this page? */ page_table[num_entry_pt].pt_acc = 0; /* page was accessed? */ page_table[num_entry_pt].pt_dirty = 0; /* page was written? */ page_table[num_entry_pt].pt_mbz = 0; /* must be zero */ page_table[num_entry_pt].pt_global =0; /* should be zero in 586 */ page_table[num_entry_pt].pt_avail = 0; /* for programmer's use */ //gives base address of each page for each global page table page_table[num_entry_pt].pt_base = (num_global_pt*(NBPG/4) + num_entry_pt); /* location of page? */ //if((num_entry_pt%128 == 0) || num_entry_pt==1023) //kprintf("\nGPT has entries %d and its base address %d", num_entry_pt, page_table[num_entry_pt].pt_base); } global_page_table[num_global_pt] = page_table; } restore(ps); return OK; } /*------------------------------------------------------------------------- * create a page table on the fly/request *------------------------------------------------------------------------- */ pt_t* create_a_page_table(int pid, int fr_type) { int get_frame_num; pt_t* page_table; int frame_no, num_entry_pt; //kprintf("\n inside create page table"); get_frame_num = fr_type; get_frm(&get_frame_num); //get free frame and get frame no in pointer get_frame_num frame_no =get_frame_num; //extract frame number from address of get_frame_num if( frame_no == SYSERR ) { return(NULL); } set_frm_tab_upon_frame_allocation(pid, frame_no, FR_TBL); //set frame table values //gives base address of page table page_table = (pt_t*)((FRAME0+frame_no)*NBPG); //kprintf("\n Frame no %d allocated to page table address %d or page no %d ", (frame_no+FRAME0), (unsigned int)page_table, ((unsigned int)page_table/NBPG)); for( num_entry_pt=0; num_entry_pt<(NBPG/4); num_entry_pt++) { page_table[num_entry_pt].pt_pres = 0; /* page is present? */ page_table[num_entry_pt].pt_write = 0; /* page is writable? */ page_table[num_entry_pt].pt_user = 0; /* is use level protection? */ page_table[num_entry_pt].pt_pwt = 0; /* write through for this page? */ page_table[num_entry_pt].pt_pcd = 0; /* cache disable for this page? */ page_table[num_entry_pt].pt_acc = 0; /* page was accessed? */ page_table[num_entry_pt].pt_dirty = 0; /* page was written? */ page_table[num_entry_pt].pt_mbz = 0; /* must be zero */ page_table[num_entry_pt].pt_global =0; /* should be zero in 586 */ page_table[num_entry_pt].pt_avail = 0; /* for programmer's use */ page_table[num_entry_pt].pt_base = 0; /* location of page? */ } return(page_table); } /*------------------------------------------------------------------------- * create and initialize page directory at system start up *------------------------------------------------------------------------- */ pd_t* create_page_dir(int pid) { pd_t* page_dir; int get_frame_num; STATWORD ps; int frame_no, num_entry_pd; //kprintf("\n Inside CREATE_PAGE_DIR()"); get_frame_num = FR_DIR; get_frm(&get_frame_num); //get free frame and get frame no in pointer get_frame_num disable(ps); frame_no =get_frame_num; //extract frame number from address of get_frame_num if( frame_no == SYSERR ) { return(NULL); } set_frm_tab_upon_frame_allocation(pid, frame_no, FR_DIR); //set frame table values //gives base address of page table page_dir = (pd_t*)((FRAME0+frame_no)*NBPG); //kprintf("\n Frame no %d allocated to page DIRectory address %d or page no %d \n", (frame_no+FRAME0), (unsigned int)page_dir, ((unsigned int)page_dir/NBPG)); //make entry into page directory for global page tables for( num_entry_pd=0; num_entry_pd<4; num_entry_pd++) { page_dir[num_entry_pd].pd_pres = 1; /* page table present? */ page_dir[num_entry_pd].pd_write = 1; /* page is writable? */ page_dir[num_entry_pd].pd_user = 0; /* is use level protection? */ page_dir[num_entry_pd].pd_pwt = 0; /* write through cachine for pt?*/ page_dir[num_entry_pd].pd_pcd = 0; /* cache disable for this pt? */ page_dir[num_entry_pd].pd_acc = 0; /* page table was accessed? */ page_dir[num_entry_pd].pd_mbz = 0; /* must be zero */ page_dir[num_entry_pd].pd_fmb = 0; /* four MB pages? */ page_dir[num_entry_pd].pd_global= 0; /* global (ignored) */ page_dir[num_entry_pd].pd_avail = 1; /* for programmer's use */ page_dir[num_entry_pd].pd_base = ((unsigned int)(global_page_table[num_entry_pd])/NBPG); /* location of page table? */ //kprintf("\nGlobal pt %d has page DIRectory address %d", num_entry_pd, page_dir[num_entry_pd].pd_base); } //for page tables that are not global page table and hence initialized for( num_entry_pd=4; num_entry_pd<(NBPG/4); num_entry_pd++) { page_dir[num_entry_pd].pd_pres = 0; /* page table present? */ page_dir[num_entry_pd].pd_write = 0; /* page is writable? */ page_dir[num_entry_pd].pd_user = 0; /* is use level protection? */ page_dir[num_entry_pd].pd_pwt = 0; /* write through cachine for pt?*/ page_dir[num_entry_pd].pd_pcd = 0; /* cache disable for this pt? */ page_dir[num_entry_pd].pd_acc = 0; /* page table was accessed? */ page_dir[num_entry_pd].pd_mbz = 0; /* must be zero */ page_dir[num_entry_pd].pd_fmb = 0; /* four MB pages? */ page_dir[num_entry_pd].pd_global= 0; /* global (ignored) */ page_dir[num_entry_pd].pd_avail = 0; /* for programmer's use */ page_dir[num_entry_pd].pd_base = 0; /* location of page table? */ //if((num_entry_pd%128 == 0) || num_entry_pd==1023) // kprintf("\nNormal pt %d has page DIRectory address %d", num_entry_pd, page_dir[num_entry_pd].pd_base); } restore(ps); return(page_dir); } /*------------------------------------------------------------------------- * free a page table when it is not being used *------------------------------------------------------------------------- */ int free_a_page_table(pt_t* page_table) { int returnValue = OK; //page_table = (pt_t*)((FRAME0+frame_no)*NBPG); returnValue = free_frm((((unsigned int)page_table/NBPG)-FRAME0)); return(returnValue); } int check_page_table_to_free(int frame_no, int vpno) { int proc_count, pd_count, pt_count, page_table_present; pt_t* page_table; page_table_present=0; for( proc_count=0; proc_count<NPROC; proc_count++) { if( (page_table =(pt_t*)((return_ptr_to_page_table(proc_count)*NBPG)))!=SYSERR ) for( pt_count=0; pt_count<(NBPG/4); pt_count++) { if( page_table[pt_count].pt_pres) { if( pt_count == frame_no ) { page_table[pt_count].pt_pres=0; } } } for( pt_count=0; pt_count<(NBPG/4); pt_count++) { if(page_table[pt_count].pt_pres) { page_table_present = 1; } } if(page_table_present == 1) { //kprintf("\nFreeing page table %d",((unsigned int)page_table/4096)); free_a_page_table(page_table); } } } int return_ptr_to_page_table(int pid) { int proc_count, pd_count; pd_t* page_dir; for(proc_count=0; proc_count<NPROC; proc_count++) { if(proctab[proc_count].pstate!=PRFREE) { page_dir =(( proctab[proc_count].pdbr)*4096); for( pd_count=4; pd_count<(NBPG/4); pd_count++) { if( page_dir[pd_count].pd_pres) { return(page_dir[pd_count].pd_base); } } } } return(SYSERR); } /*------------------------------------------------------------------------- * free page directory along with any page tables associated with it *------------------------------------------------------------------------- */ int free_page_directory(pd_t* page_dir) { int returnValue_page = OK; int returnValue_dir = OK; int num_entry; for( num_entry = 0; num_entry<(NBPG/4); num_entry++) { //page directory contains a page table entry, so free each page table too returnValue_page = free_a_page_table((pt_t*)&(page_dir[num_entry])); } returnValue_dir = free_frm((((unsigned int)page_dir/NBPG)-FRAME0)); if( (returnValue_page == SYSERR) || (returnValue_dir == SYSERR) ) { returnValue_page = SYSERR; } /*------------------------------------------------------------------------------------------------- check for return value here, multiple return value for page, check for multiple return values --------------------------------------------------------------------------------------------------*/ return(returnValue_page); }
C
// C++ program to print pattern that first reduces 5 one // by one, then adds 5. Without any loop #include <iostream> using namespace std; // Recursive function to print the pattern. // n indicates input value // m indicates current value to be printed // flag indicates whether we need to add 5 or // subtract 5. Initially flag is true. void printPattern(int n, int m, bool flag) { // Print m. cout << m << " "; // If we are moving back toward the n and // we have reached there, then we are done if (flag == false && n ==m) return; // If we are moving toward 0 or negative. if (flag) { // If m is greater, then 5, recur with true flag if (m-5 > 0) printPattern(n, m-5, true); else // recur with false flag printPattern(n, m-5, false); } else // If flag is false. printPattern(n, m+5, false); } // Driver Program int main() { int n = 16; printPattern(n, n, true); return 0; }
C
// === Source file: sorting.c === #include "sorting.h" double timestamp(void) { struct timeval tp; gettimeofday(&tp, NULL); return ((double)(tp.tv_sec * 1000.0 + tp.tv_usec / 1000.0)); } void print_array(int *arr, int size) { printf("["); for (int i = 0; i < size - 1; i++) printf("%i ", arr[i]); printf("%i]\n", arr[size - 1]); } int *make_array(int size) { int *arr = (int *)malloc(size * sizeof(int)); if (!arr) { fprintf(stderr, "Memory allocation error!\n"); exit(1); } update_array(arr, size); return arr; } void update_array(int *arr, int size) { for (int i = 0; i < size; i++) arr[i] = (rand() % (size * 3)); } void swap_array(int *arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } void bubble_sort(int *arr, int size) { if (!arr) return; for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - 1 - i; j++) { if (arr[j] > arr[j + 1]) swap_array(arr, j, j + 1); } } } void selection_sort(int *arr, int size) { if (!arr) return; for (int i = 0, j = 0, min = 0; i < size - 1; i++) { for (j = i + 1, min = i; j < size; j++) { if (arr[j] < arr[min]) min = j; } if (min != i) swap_array(arr, i, min); } } void insertion_sort(int *arr, int size) { if (!arr) return; for (int i = 1, j; i < size; i++) { int key = arr[i]; for (j = i; (j > 0) && (key < arr[j - 1]); j--) arr[j] = arr[j - 1]; if (j != i) arr[j] = key; } } void merge_array(int *arr, int begin, int mid, int end) { int w[end - begin + 1]; int i = begin, j = mid + 1, k = 0; while (i <= mid && j <= end) { if (arr[i] <= arr[j]) w[k++] = arr[i++]; else w[k++] = arr[j++]; } while (i <= mid) w[k++] = arr[i++]; while (j <= end) w[k++] = arr[j++]; for (i = begin; i <= end; i++) arr[i] = w[i - begin]; } void merge_sort(int *arr, int begin, int end) { if (begin < end) { int mid = begin + (end - begin) / 2; merge_sort(arr, begin, mid); merge_sort(arr, mid + 1, end); merge_array(arr, begin, mid, end); } } int pivot(int *arr, int begin, int end) { int pivot = arr[begin]; int i, j; for (i = end, j = end; j > begin; j--) { if (arr[j] > pivot) swap_array(arr, i--, j); } swap_array(arr, i, begin); return i; } void quick_sort(int *arr, int begin, int end) { if (begin < end) { int pivot_index = pivot(arr, begin, end); quick_sort(arr, begin, pivot_index - 1); quick_sort(arr, pivot_index + 1, end); } } void print_heap(Heap *H) { printf("["); for (int i = 1; i <= H->arr_size - 1; i++) printf("%i ", H->arr[i]); printf("%i]\n", H->arr[H->arr_size]); } void make_heap(Heap *H, int size) { H->arr_size = size; H->heap_size = size; H->arr = make_array(H->arr_size + 1); } void max_heapify(Heap *H, int i) { int left = 2 * i, right = 2 * i + 1, largest = i; if (left <= H->heap_size && H->arr[left] > H->arr[i]) largest = left; if (right <= H->heap_size && H->arr[right] > H->arr[largest]) largest = right; if (largest != i) { swap_array(H->arr, i, largest); max_heapify(H, largest); } } void build_max_heap(Heap *H) { for (int i = H->heap_size / 2; i >= 1; i--) max_heapify(H, i); } void heap_sort(Heap *H) { build_max_heap(H); while (H->heap_size >= 2) { swap_array(H->arr, H->heap_size--, 1); max_heapify(H, 1); } }
C
#include "libmx.h" void *mx_memmem(const void *big, size_t big_len, const void *little, size_t little_len) { char *b = (char*) big; char *l = (char*) little; bool flag; size_t i; size_t j; if (little_len == 0) return NULL; for (i = 0; i < big_len; i++, b++) { flag = true; for (j = 0; j < little_len; j++) { if (b[j] != l[j]) flag = false; } if (flag) return b; } return NULL; }
C
#define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 1000 typedef int ElemType; typedef int Status; typedef struct { ElemType data; int cur; }Component, StaticLinkList[MAXSIZE]; Status InitList(StaticLinkList space)/*初始化一个静态数组列表*/ { int i; for (i = 0; i < MAXSIZE - 1; ++i) space[i].cur = i + 1; space[MAXSIZE - 1].cur = 0;/*首位相连,构成环形的静态的线性表*/ return OK; } int Malloc_SLL(StaticLinkList space)/*模拟malloc动态分配内存,space[0].cur中记录着第一个可以被利用的空闲空间*/ { int i = space[0].cur; while (space[0].cur) space[0].cur = space[i].cur; return i; } Status ListInsert(StaticLinkList L, int i, ElemType e)/*在i-1 与 i 之间插入数据e*/ { int j, k, l; k = MAXSIZE - 1; if (i < 1 || i > ListLength(L) + 1) return ERROR; j = Malloc_SLL(L); if (j) { L[j].data = e; for (l = 1; l <= i - 1; ++l) k = L[k].cur; L[j].cur = L[k].cur; L[k].cur = j; return OK; } return ERROR; } Status ListDelete (StaticLinkList L, int i) { int j, k, i; if (i < 1 || i > ListLength(L)) return ERROR; k = MAXSIZE - 1;/*因为L[MAXSIZE - 1].cur是指向头结点的*/ for (j = 1; j <= i - 1; ++j) k = L[k].cur; j = L[k].cur; L[k].cur = L[j].cur; Free_SLL(L, j); return OK; } void Free_SLL(StaticLinkList L, int k)/*删除j这个节点*/ { space[k].cur = space[0].cur;/*头结点中记录的是当前空闲的空间,并方便利用*/ space[0].cur = k; } void ListLength(StaticLinkList L)/*计算该静态链表长度*/ { int j = 0; int i = L[MAXSIZE - 1].cur; while (i) { i = L[i].cur; ++j; } return j; }
C
#include <stdio.h> #include <ctype.h> int read_line(char str[], int n); void capitalize(char str[], int n); #define MSG_LEN 60 int main(void) { char s[MSG_LEN+1]; int n; n = read_line(s, MSG_LEN); printf("%s", s); printf("\n"); capitalize(s, n); printf("%s", s); printf("\n"); return 0; } int read_line(char str[], int n) { int ch, i = 0; while ((ch = getchar()) != '\n') { if (i < n) str[i++] = ch; } str[i] = '\0'; return i; } void capitalize(char str[], int n) { int i = 0; while (str[i]) { if (isalpha(str[i])) str[i] = toupper(str[i]); i++; } }
C
/* ** EPITECH PROJECT, 2019 ** Title ** File description: ** Description */ #include <stdlib.h> #include "istl/private/p_list.h" #include "istl/utility.h" list_t *list_create(meta_bundle_t meta) { list_t *list = malloc(sizeof(list_t)); if (list == NULL) return (NULL); list->size = 0; list->begin = it_allocate(0, 0); list->end = list->begin; list->type_meta = meta; it_couple(list->begin, list->end); return (list); } void **list_to_array(list_t *list) { unsigned int size; dsize_t dsize; void **array = 0; iterator_t it; if (list == 0 || list_len(list) < 1) return (0); it = list_begin(list); dsize = list->type_meta.data_size; size = list_len(list); array = (void **)malloc(sizeof(void *) * size); for (int i = 0; !list_final(list, it); i++) { if (list->type_meta.copy == 0) array[i] = mem_copy(list_data(it), dsize); else array[i] = list->type_meta.copy(list_data(it)); it = it_next(it); } return (array); } list_t *list_copy(list_t *list) { iterator_t begin; iterator_t end; list_t *nlist; if (list == 0) return (0); begin = list_begin(list); end = list_end(list); nlist = list_splice(list, begin, end); nlist->type_meta = list->type_meta; return (nlist); } void list_merge(list_t *lhs, list_t *rhs) { iterator_t begin; if (lhs == 0 || rhs == 0) return; begin = list_begin(rhs); for (iterator_t it = begin; !list_final(rhs, it); it = it_next(it)) list_push_back(lhs, list_data(it)); } void list_push_back(list_t *list, void const *data_p) { iterator_t *it = 0; dsize_t sizeof_data; void *data = NULL; cpy_constructor_ft copy; if (list == 0) return; copy = list->type_meta.copy; sizeof_data = list->type_meta.data_size; data = (copy == 0) ? mem_copy(data_p, sizeof_data) : copy(data_p); it = it_allocate(data, sizeof_data); if (list->size == 0) { list->begin = it; it_couple(list->begin, list->end); } else { it_couple(it_get_prior(list->end), it); it_couple(it, list->end); } list->size += 1; }
C
/** * @file * @author * * @brief Biblioteca para operações diversas. * */ #ifndef UTILS_H #define UTILS_H #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> static const char NEWLINE = '\n'; static const char ENDSTRING = '\0'; /** * @brief Limpa o buffer de entrada de dados. * @warning Caso não exista nenhuma informação no buffer, o programa pode * ficar a aguardar que exista informação no buffer. * * Exemplo: * @code * char car: * * car = getchar(); * limparBufferEntradaDados(); * @endcode */ void limparBufferEntradaDados(); /** * Lê uma cadeia de caracteres (string) através da stream stdin * * @param frase - Apontador para a frase lida. * @param tamanho - Tamanho máximo da frase a ser lida. @warning: O tamanho da frase deve ter em conta o espaço para o carácter de término da string ('\0') * @return 1 em caso de leitura com sucesso, 0 caso ocorra um erro. * * Exemplo: * char nome[100 + 1]; * printf("Introduza o seu nome: "); * if (lerFrase (nome, 100 + 1) == true) * printf("O nome lido e: %s", nome); */ bool lerFrase(char * const frase, const unsigned int tamanho); #ifdef __cplusplus } #endif #endif /* UTILS_H */
C
#include <stdio.h> int factorial(int n); int main(void) { for(int i=1;i<=10;i++) { printf("%d! = %d\n", i, factorial(i)); } return 0; } int factorial(int n) { if(n<=1) return(1); else return(n * factorial(n-1)); }
C
# include <stdio.h> int main() { int n; scanf("%d", &n); int id[n], grade[n]; int k = 0; for (int i=0; i < n; i++) { grade[i] = 0; id[i] = 0; } for (int i=0; i < n; i++) { int id_buffer, grade_buffer, buffer; scanf("%d-%d %d", &id_buffer, &buffer, &grade_buffer); int j; for (j=0; j < k; j++) { if (id[j] == id_buffer) { grade[j] += grade_buffer; break; } } if (j >= k) { id[k] = id_buffer; grade[k] = grade_buffer; k++; } } int max_id = 0, max = 0; for (int i=0; i < k; i++) if (grade[i] > max) { max = grade[i]; max_id = id[i]; } printf("%d %d\n", max_id, max); return 0; }
C
/* process devide then percent */ /* This peace of code was used to creat the logical pattern * for the program lgates.c so that the information of how * well the person being tested could see there results. */ #include "stdio.h" main() { int endcount; int num_right; /* variable declaration */ int display; float numb1; float numb2; float numb3; endcount = 25; /* This makes sure that the program is */ num_right = 12; /* operating how it should be */ printf("endcount = %d num_right = %d\n", endcount, num_right); numb1 = num_right; printf("numb1 = %f\n", numb1); numb2 = endcount; printf("numb2 = %f\n", numb2); numb3 = numb1 / numb2; printf("numb3 = %f\n", numb3); display = numb3 * 100; printf("display %d\n", display); }
C
#include <iostream> using namespace std; int main() { int i,k,j,m,n,l; cout<<"enter row\n"; cin>>n; l=n; for(i=1 ; i<=n ; i++) { m=n; for(j=1 ; j<=n*m ; j++) { for(k=l ; k >=1 ; k--) { cout<<m; } m--; } l--; cout<<endl; } }
C
#include <stdio.h> #include <stdlib.h> #include "menu.h" #include "dicionario.h" #include "leituraTR.h" #include "DistEuclid.h" int baz; //O(1) int main (){ FILE *bowA = NULL; //O(1) FILE *bowB = NULL; //O(1) int op=1, n = 0, *ContA, *ContB, bowAn = 0, bowBn = 0; //O(1) char nomeD[30], nomeBowA[30], nomeBowB[30]; //O(3) while(op!=6) { menu(); //O(9) scanf("%d", &op); system("clear || cls") ; //O(1) switch (op) //O(n²) -> complexidade do switch (maior complexidade dentre as opções) { case 1: dicionario(&n, nomeD); //O(n) <- onde n é a uma estrura de repetição simples, dependendo do número de palavras de um arquivo ContA = (int*) calloc(n, sizeof(int)); ContB = (int*) calloc(n, sizeof(int)); break; case 2: if( n!= 0){ //O(n²) <- estrura de repetições aninhadas,e ambas dependentes do número de palavras do arquivo em todo caso bowA=leituraTR(nomeD, nomeBowA, ContA, n, 1); bowAn = 1; } else { printf("Você não indicou nenhum dicionário. Indique e tente novamente. \n"); } break; case 3: if( n!= 0){ //O(n²) <- estrura de repetições aninhadas,e ambas dependentes do número de palavras do arquivo em todo caso bowB=leituraTR(nomeD, nomeBowB, ContB, n, 2); bowBn = 1; } else { printf("Você não indicou nenhum dicionário. Indique e tente novamente. \n"); } break; case 4: if(bowAn == 0){ printf("Indique o texto A primeiramente.\n"); } else if(bowBn == 0){ printf("Indique o texto B primeiramente.\n"); } else { Exibir_Bows(nomeD, ContA, ContB, n); } //O(n) <- onde n é a uma estrura de repetição simples, dependendo do número de palavras de um arquivo break; case 5: if(bowAn == 0){ printf("Indique o texto A primeiramente.\n"); } else if(bowBn == 0){ printf("Indique o texto B primeiramente.\n"); } else { DistEuclid(n, ContA, ContB); } //O(n) <- onde n é a uma estrura de repetição simples, dependendo do número de palavras de um arquivo break; case 6: printf("Obrigado pela visita e volte sempre!!!\n"); //O(1) break; default: break; } } //Complexidade do while: Ω(6*n²) ->Melhor dos casos usuário utiliza cada funcionalidade uma vez, // O(n*2n²) pior dos casos usuário ultiliza n vezes; free (ContA); //O(1) free(ContB); //O(1) return 0; } //Complexidade O = O(n*(n²+10) + O(10) = O(n³) //Complexidade Ω = Ω(6*(n²+10) + Ω(10) = Ω(n²) //Complexidade Θ = Θ(z(n²+10) + Θ(10) = Θ(z*n²) -> onde 6 < z < n
C
/* * appbase.c * * Created on: 31 May 2016 * Author: ajuaristi <[email protected]> */ #include <curl/curl.h> #include <json-c/json_object.h> #include <modp_b64.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> #include "main.h" #include "utils.h" #include "frame.h" #include "json-streamer.h" #include "appbase.h" #define APPBASE_API_URL "scalr.api.appbase.io" #define APPBASE_PATH "pic/1" struct appbase { char *url; CURL *curl; json_object *json; }; static char *appbase_generate_url(const char *app_name, const char *username, const char *password, bool streaming) { char *url = NULL; if (!app_name || !username || !password) goto fatal; #ifdef _GNU_SOURCE if (asprintf(&url, (streaming ? "https://%s:%s@%s/%s/%s/?stream=true" : "https://%s:%s@%s/%s/%s"), username, password, APPBASE_API_URL, app_name, APPBASE_PATH) == -1) goto fatal; #else #error "Sorry. Non-GNU environments are not yet supported." #endif return url; fatal: return NULL; } /* * I know field 'json' is const char*. It could be char* as well. * But we're using the same pointer both to read and to write, * and so I prefer to keep it const and let the compiler warn me * when I write data when I should only read it (because that signals * poor coding practice, and I'm probably clobbering something important), * and tell it explicitly that I know it will go well when writing. * * So in 'reader_cb', we make sure we only read. * In 'writer_cb' we make explicit casting to (char *) to skip * compiler warnings. * * I've seen tricks such as this: http://stackoverflow.com/questions/8836418/is-const-casting-via-a-union-undefined-behaviour * But don't seem to make much difference in practice. */ struct json_internal { const char *json; size_t length; off_t offset; struct json_streamer *json_streamer; appbase_frame_cb_t frame_callback; void *userdata; }; /* * Callback for libcurl. This should fill 'buffer' with the data we want to send * and return the actual number of bytes written. * 'instream' holds user-defined data, a pointer to a 'json_internal' struct * in our case. */ static size_t reader_cb(char *buffer, size_t size, size_t nitems, void *instream) { size_t should_write = size * nitems; struct json_internal *json = (struct json_internal *) instream; if (!instream || !json->json || json->length <= 0 || should_write <= 0) return CURL_READFUNC_ABORT; if (json->offset >= json->length) { /* * There's no more data to send - we've sent it all. * Tell libcurl we're done. */ return 0; } if (json->offset + should_write > json->length) should_write = json->length - json->offset; memcpy(buffer, json->json + json->offset, should_write); json->offset += should_write; return should_write; } /* * Writer callback for libcurl. Serves two purposes. * * When 'userdata' == NULL, this is just a sink to prevent libcurl from printing * data received from the server on screen (when debug mode is disabled). We just set * CURLOPT_WRITEFUNCTION to this function, so that data to be written will be passed * to us instead. This is handled by appbase_push_frame(). * * When 'userdata' != NULL, then it should be a struct json_internal. This means cURL * issued a GET request, and 'ptr' holds the response body of the server, which we should * store into the json_internal struct. This is handled by appbase_fill_frame(). */ static size_t writer_cb(unsigned char *ptr, size_t size, size_t nmemb, void *userdata) { struct json_internal *json = NULL; size_t ttl_size = size * nmemb; unsigned char *err = NULL; if (!userdata || !ttl_size || !ptr) goto end; json = (struct json_internal *) userdata; if (!json_streamer_push(json->json_streamer, ptr, ttl_size)) { err = json_streamer_get_last_error(json->json_streamer, ptr, ttl_size); fprintf(stderr, "JSON ERROR: %s\n", err); json_streamer_free_last_error(json->json_streamer, err); } end: return ttl_size; } static void frame_callback(const char *frame_data, size_t len, void *userdata) { size_t image_len; char *image; struct json_internal *json = userdata; if (!json) return; if (frame_data && len) { /* 'image' should be freed by the client */ image_len = modp_b64_decode_len(len); image = ec_malloc(image_len); image_len = modp_b64_decode(image, frame_data, len); if (image_len != -1) json->frame_callback(image, image_len, json->userdata); else goto fail; /* Success! */ return; } fail: /* * Failure * If image decoding failed, call frame_callback() with a NULL argument, * to let the client know about the error. */ json->frame_callback(NULL, 0, json->userdata); } void appbase_close(struct appbase *ab) { if (ab) { if (ab->curl) curl_easy_cleanup(ab->curl); if (ab->url) free(ab->url); if (ab->json) json_object_put(ab->json); ab->curl = NULL; ab->url = NULL; ab->json = NULL; free(ab); } } /* * libcurl keeps the socket open when possible */ struct appbase *appbase_open(const char *app_name, const char *username, const char *password, bool enable_streaming) { struct appbase *ab = ec_malloc(sizeof(struct appbase)); /* Initialize libcurl, and set up our Appbase REST URL */ ab->curl = curl_easy_init(); if (!ab->curl) goto fatal; curl_easy_setopt(ab->curl, CURLOPT_VERBOSE, 0L); curl_easy_setopt(ab->curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(ab->curl, CURLOPT_WRITEFUNCTION, writer_cb); curl_easy_setopt(ab->curl, CURLOPT_WRITEDATA, NULL); ab->url = appbase_generate_url(app_name, username, password, enable_streaming); if (!ab->url) goto fatal; /* Create our base JSON object */ ab->json = json_object_new_object(); if (!ab->json) goto fatal; return ab; fatal: appbase_close(ab); return NULL; } void appbase_enable_progress(struct appbase *ab, bool enable) { if (ab && ab->curl) curl_easy_setopt(ab->curl, CURLOPT_NOPROGRESS, !enable); } void appbase_enable_verbose(struct appbase *ab, bool enable) { if (ab && ab->curl) { curl_easy_setopt(ab->curl, CURLOPT_VERBOSE, enable); curl_easy_setopt(ab->curl, CURLOPT_WRITEFUNCTION, fwrite); curl_easy_setopt(ab->curl, CURLOPT_WRITEDATA, stderr); } } bool appbase_push_frame(struct appbase *ab, const unsigned char *data, size_t length, struct timeval *timestamp) { CURLcode response_code; struct json_internal json; size_t b64_size = 0; char *b64_data; if (!ab || !ab->curl || !ab->url || !ab->json || !data || !length || !timestamp) return false; /* Transform raw frame data into base64 */ b64_size = modp_b64_encode_len(length); b64_data = ec_malloc(b64_size); if (modp_b64_encode(b64_data, (char *) data, length) == -1) return false; /* * Generate a JSON object with the format: * * { * "image": "<data>", * "sec": "<seconds>", * "usec": "<milliseconds>" * } */ json_object_object_add(ab->json, AB_KEY_IMAGE, json_object_new_string(b64_data)); json_object_object_add(ab->json, AB_KEY_SEC, json_object_new_int64(timestamp->tv_sec)); json_object_object_add(ab->json, AB_KEY_USEC, json_object_new_int64(timestamp->tv_usec)); json.json = json_object_to_json_string_ext(ab->json, JSON_C_TO_STRING_PLAIN); json.length = strlen(json.json); json.offset = 0; curl_easy_setopt(ab->curl, CURLOPT_URL, ab->url); curl_easy_setopt(ab->curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(ab->curl, CURLOPT_INFILESIZE, json.length); curl_easy_setopt(ab->curl, CURLOPT_READDATA, &json); curl_easy_setopt(ab->curl, CURLOPT_READFUNCTION, reader_cb); response_code = curl_easy_perform(ab->curl); /* * No need to free the JSON string. * We call json_object_put() on the root JSON object in appbase_close(), * and it will release the whole JSON object, including this string * for us. */ json.length = 0; json.offset = 0; free(b64_data); return (response_code == CURLE_OK); } bool appbase_stream_loop(struct appbase *ab, appbase_frame_cb_t fcb, void *userdata) { CURLcode response_code; struct json_internal json_response; if (!ab || !ab->curl || !fcb) return false; json_response.json = NULL; json_response.length = 0; json_response.offset = 0; json_response.frame_callback = fcb; json_response.userdata = userdata; json_response.json_streamer = json_streamer_init(frame_callback, &json_response); if (!json_response.json_streamer) return false; curl_easy_setopt(ab->curl, CURLOPT_URL, ab->url); curl_easy_setopt(ab->curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(ab->curl, CURLOPT_WRITEFUNCTION, writer_cb); curl_easy_setopt(ab->curl, CURLOPT_WRITEDATA, &json_response); /* * Here, curl_easy_perform() should block until the remote host closes the connection, * or we call curl_easy_cleanup() (this happens in appbase_close()). */ response_code = curl_easy_perform(ab->curl); /* Clean up */ json_streamer_destroy(json_response.json_streamer); return (response_code == CURLE_OK); }
C
#include<stdio.h> #include<stdlib.h> struct circle{ int x,y; int radius; struct circle* next; }; int main () { struct circle *a,*b,*c,*current; a = (struct circle *)malloc(sizeof(struct circle)); printf("пJĤ@Ӷꪺ(x,y):"); scanf("%d %d",&a->x,&a->y); printf("пJĤ@Ӷꪺb|:"); scanf("%d",&a->radius); a->next = NULL; b=(struct circle *)malloc(sizeof(struct circle)); printf("пJĤGӶꪺ(x,y):"); scanf("%d %d",&b->x,&b->y); printf("пJĤGӶꪺb|:"); scanf("%d",&b->radius); b->next=NULL; a->next =b; c=(struct circle *)malloc(sizeof(struct circle)); printf("пJĤTӶꪺ(x,y):"); scanf("%d %d",&c->x,&c->y); printf("пJĤTӶꪺb|:"); scanf("%d",&c->radius); c->next=NULL; b->next=c; current=a; int i=1; while(current != NULL){ printf("%dӶꪺ߬(%d %d),b|%d\n", i,current->x,current->y,current->radius); i ++; current=current->next; } free(a); free(b); free(c); system("pause"); return 0; }
C
/* exploitme coded in a hurry by Yoann Guillot and Julien Tinnes, used 'man select_tut' as skeleton */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <string.h> #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <sys/mman.h> #include <malloc.h> #define LISTEN_PORT 4545 int main(void) { struct sockaddr_in a; int s, mysock; int yes, ret, pagesize; void *buf; pagesize = sysconf(_SC_PAGE_SIZE); if (pagesize == -1) { perror("pagesize"); return -1; } if (pagesize < 4096) pagesize=(4096/pagesize+1)*pagesize; printf("Detected pagesize: %d\n", pagesize); buf=memalign(pagesize, pagesize); if (buf == NULL) { perror("memalign"); return -1; } if ((s = socket (AF_INET, SOCK_STREAM, 0)) < 0) { perror ("socket"); return -1; } yes = 1; if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (char *) &yes, sizeof (yes)) < 0) { perror ("setsockopt"); close (s); return -1; } memset (&a, 0, sizeof (a)); a.sin_port = htons (LISTEN_PORT); a.sin_family = AF_INET; if (bind (s, (struct sockaddr *) &a, sizeof (a)) < 0) { perror ("bind"); close (s); return -1; } printf ("Send your shellcode to port %d\n", (int) LISTEN_PORT); listen (s, 10); for (;;) { mysock=accept(s, NULL, NULL); if (mysock == -1) { perror("accept"); close(s); return -1; } if (!fork()) { printf("Got new connexion\n"); close(s); switch (yes=read(mysock, buf, pagesize)) { case -1: perror("read"); case 0: close(mysock); close(s); return -1; } printf("Read %d bytes\n", yes); /* This has the useful side effect of flushing the cache on architectures such as MIPS! */ ret=mprotect(buf, pagesize, PROT_READ|PROT_WRITE|PROT_EXEC); if (ret) { perror("mprotect"); return -1; } ((void (*)())buf)(); return 42; } else close(mysock); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> // Prompt was not a valid choice, notify user. void invalidPrompt(void) { printf("You entered an incorrect choice. Try again.\n"); return; }
C
#include <stdio.h> #include <math.h> #include <assert.h> #include <time.h> #include <stdlib.h> int MAXNUM = 50000000; int main(int argc, char *argv[]){ FILE *fp=NULL; assert((fp=fopen("./largdata.txt","w")) != NULL); int i=0,tmp,j=0,k=0; char ch[5] = {NULL}; srand((int)time(0)); if (argc > 1) MAXNUM = atoi(argv[1]); while(i<MAXNUM){ tmp = rand(); for(k=0;k<5;k++){ for(j=0;j<3;j++){ ch[j] = 'a' + rand()%26; } ch[3]=' '; ch[4] = '\0'; assert(fprintf(fp,"%s",ch)); } assert(fprintf(fp,"\n")); i++; } fclose(fp); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* env.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ghan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/24 13:24:31 by yongjule #+# #+# */ /* Updated: 2021/10/01 20:30:26 by ghan ### ########.fr */ /* */ /* ************************************************************************** */ #include "builtin.h" extern int g_exit_code; int env(const char *path, char *const argv[], char *const envp[]) { int idx; if (!path || !argv || !envp) { g_exit_code = is_error_no_exit("export : ", NULL, "pass valid args to builtin functions", EXIT_FAILURE); return (g_exit_code); } g_exit_code = EXIT_SUCCESS; if (argv[1]) { is_error_no_exit("env : ", argv[1], ": env in minishell takes no arguments or options", EXIT_FAILURE); g_exit_code = EXIT_FAILURE; } else { idx = -1; while (envp[++idx]) { if (ft_strchr(envp[idx], '=')) printf("%s\n", envp[idx]); } } return (g_exit_code); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rotation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hvashchu <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/27 18:14:54 by hvashchu #+# #+# */ /* Updated: 2017/10/27 18:14:56 by hvashchu ### ########.fr */ /* */ /* ************************************************************************** */ #include "rtv1.h" static void rotation_x(t_vector *v, double a) { t_vector tmp; double alpha; alpha = a * M_PI / 180; tmp = *v; v->y = tmp.y * cos(alpha) - tmp.z * sin(alpha); v->z = tmp.y * sin(alpha) + tmp.z * cos(alpha); } static void rotation_y(t_vector *v, double b) { t_vector tmp; double alpha; alpha = b * M_PI / 180; tmp = *v; v->x = tmp.x * cos(alpha) + tmp.z * sin(alpha); v->z = -tmp.x * sin(alpha) + tmp.z * cos(alpha); } static void rotation_z(t_vector *v, double c) { t_vector tmp; double alpha; alpha = c * M_PI / 180; tmp = *v; v->x = tmp.x * cos(alpha) - tmp.y * sin(alpha); v->y = tmp.x * sin(alpha) + tmp.y * cos(alpha); } void rotate(t_vector *v, double a, double b, double c) { rotation_x(v, a); rotation_y(v, b); rotation_z(v, c); } void calc_discriminant(double a, double b, double c, t_mlx *new) { double discriminant; double tt[2]; discriminant = b * b - 4 * a * c; if (discriminant < 0) { new->intersection = 0; return ; } else { tt[0] = (-b + sqrt(discriminant)) / (2 * a); tt[1] = (-b - sqrt(discriminant)) / (2 * a); new->intersection = 1; if (tt[0] > 0.001 && tt[0] < new->t) new->t = tt[0]; if (tt[1] > 0.001 && tt[1] < new->t) new->t = tt[1] - 0.1; else new->intersection = 0; if (new->t > new->dist) new->intersection = 0; } }
C
#include "mynet.h" int main(void){ char *buf, *p; char arg1[MAXLINE], arg2[MAXLINE], content[MAXLINE]; int n1=0,n2=0; if((buf=getenv("QUERY_STRING")) != NULL){ p = strchr(buf, '&'); *p = '\0'; strcpy(arg1, buf); strcpy(arg2, p+1); n1 = atoi(arg1); n2 = atoi(arg2); } sprintf(content,"QUERY_STRING=%s",buf); sprintf(content,"Welcome to add.com: "); sprintf(content,"%sTHE Internet addition portal.\r\n<p>",content); sprintf(content,"%sThe answer is %d + %d = %d\r\n<p>", content,n1,n2,n1+n2); sprintf(content,"%sThanks for visiting!\r\n",content); printf("Connection: close\r\n"); printf("Contetn-length:%d\r\n",(int)strlen(content)); printf("Content-type: text/html\r\n\r\n"); printf("%s",content); fflush(stdout); exit(0); }
C
#include<stdio.h> #include<stdlib.h> int selection_sort(int a[],int h) { int i,j,k=0,t; for(i=0;i<h-1;i++) { for(j=i+1;j<h;j++) { if(++k&&a[j]<a[i]){ t=a[j]; a[j]=a[i]; a[i]=t;} } } return k; } int main(){ int *a,n,i,t; scanf("%d",&n); a=(int*)malloc(n*sizeof(int)); for(i=0;i<n;i++) scanf("%d",&a[i]); t=selection_sort(a,n); for(i=0;i<n;i++){ printf("%d ",a[i]);} printf("\n%d",t); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_export.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mjung <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/27 07:12:09 by mjung #+# #+# */ /* Updated: 2021/09/27 08:29:06 by mjung ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" char *make_export_string(t_list *list_env, char *target_key) { char *line; t_env *target_env; line = NULL; target_env = find_env_by_key(list_env, target_key); line = ft_strjoin(line, ft_strdup("declare -x ")); line = ft_strjoin(line, ft_strdup(target_env->key)); if (target_env->value) { line = ft_strjoin(line, ft_strdup("=\"")); line = ft_strjoin(line, ft_strdup(target_env->value)); line = ft_strjoin(line, ft_strdup("\"")); } line = ft_strjoin(line, ft_strdup("\n")); return (line); } char *found_next_key(t_list *env, char *prev_key) { char *result_key; result_key = NULL; while (env) { if (result_key == NULL && ft_strcmp(prev_key, ((t_env *)env->content)->key) < 0) result_key = ((t_env *)env->content)->key; else { if (ft_strcmp(prev_key, ((t_env *)env->content)->key) < 0 && ft_strcmp(result_key, ((t_env *)env->content)->key) > 0) result_key = ((t_env *)env->content)->key; } env = env->next; } return (result_key); } char *show_env_by_export(t_list *env) { char *prev_key; char *current_key; char *result; int idx; idx = -1; prev_key = NULL; result = NULL; while (ft_lstsize(env) > (++idx)) { current_key = found_next_key(env, prev_key); result = ft_strjoin(result, make_export_string(env, current_key)); prev_key = current_key; } return (result); } void div_key_value(char *arg, char **key, char **value) { int separator_idx; separator_idx = 0; while (arg[separator_idx] && arg[separator_idx] != '=' ) separator_idx++; *key = ft_substr(arg, 0, separator_idx); if (ft_strlen(arg) - separator_idx) *value = ft_substr( arg, separator_idx + 1, ft_strlen(arg) - separator_idx); else *value = NULL; } void ft_export(t_simple_cmd *simple_cmd, t_list *env, t_mcb *mcb) { int idx; char *key; char *value; char *output; idx = 0; if (simple_cmd->argv[1] == NULL) { output = show_env_by_export(env); write(mcb->fd_output, output, ft_strlen(output)); exit(0); } while (simple_cmd->argv[++idx]) { key = NULL; value = NULL; div_key_value(simple_cmd->argv[idx], &key, &value); if (check_env_key(key)) env_key_error("export", key); else set_env(&env, key, value); free(key); free(value); } g_global.rtn = 0; }
C
/*------------------------------------------------------------------------------------------------ * Author : Rammya Dharshini K * Date : Sat 17 Jul 2021 15:45:04 * File : c_sample_Chapter-1_Program-9_type_modifiers.c * Title : C basic datatypes * Description : A simple program exploring the basic C data types. C supports two basic * datatypes hold integral and real objects as int and float (single precision). * The char falls under the integral category. Any variable defined with integral * datatypes can be modified for its signedness and width properties. This * example demonstrates the storage modification of variable. *-----------------------------------------------------------------------------------------------*/ #include <stdio.h> int main() { /* * Request the compiler to provide a CPU register space if available * The allocation become auto on failure to get register space */ register int number; printf("Enter a number: "); /* Cannot access the address of a variable specified with register keyword */ scanf("%d", &number); printf("You entered: %d", number); return 0; }
C
/* * Alauddin Ansari * 2018-11-20 * ATtiny85 Watchdog settings */ #include <avr/sleep.h> #include <avr/wdt.h> #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif // Watchdog Interrupt Service / is executed when watchdog timed out ISR(WDT_vect) {} // set system into the sleep state // system wakes up when wtchdog is timed out void system_sleep() { cbi(ADCSRA,ADEN); // switch Analog to Digital Converter (ADC) OFF set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here sleep_enable(); sleep_mode(); // System sleeps here sleep_disable(); // System continues execution here when watchdog timed out sbi(ADCSRA,ADEN); // switch Analog to Digital Converter (ADC) ON } // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms // 6=1sec, 7=2sec, 8=4sec, 9=8sec void setup_watchdog(int ii) { byte bb; int ww; if (ii > 9 ) ii=9; bb=ii & 7; if (ii > 7) bb|= (1<<5); bb|= (1<<WDCE); ww=bb; MCUSR &= ~(1<<WDRF); // start timed sequence WDTCR |= (1<<WDCE) | (1<<WDE); // set new watchdog timeout value WDTCR = bb; WDTCR |= _BV(WDIE); }
C
#pragma once #include<string.h> #include<stdio.h> #include "MU_declaration.h" static char PATH[256]; inline void musnake::initPath(char* path) { char* p = PATH; strcpy(PATH, path); while (*p)p++; while (*p != '\\' && *p != '/')p--; *(++p) = 0; } inline void musnake::catPath(char* dest, char* relative) { strcpy(dest, PATH); strcat(dest, relative); char* cp = dest; while (*cp) { #if defined(_WIN32) || defined(_WIN64) if (*cp == '/') *cp = '\\'; #elif defined(_linux) || defined(_linux_) || defined(_unix) || defined(_unix_) if (*cp == '\\') *cp = '/'; #endif cp++; } } inline void int2str(char* dest, int num) { sprintf(dest, "%d", num); } inline int str2int(char* src) { int i; sscanf(src, "%d", &i); return i; }
C
// Lined list create,display,insert,insert_At_End, delete, n_th_node, palindrom operations #include<stdio.h> #include<stdlib.h> struct ListNode{ int data; struct ListNode *next; }; struct ListNode *head = NULL,*tail = NULL; struct ListNode *getNodeMemory(){ struct ListNode *temp; temp = (struct ListNode *)malloc(sizeof(struct ListNode)); return temp; } struct ListNode *mid(struct ListNode *head){ struct ListNode *t1=head,*t2=head; int flag = 1; while(t1){ if(flag){ t1 = t1->next; flag = 0; }else{ t1 = t1->next; t2 = t2->next; flag = 1; } } return t2; } void create(){ struct ListNode *temp; int data; printf("Enter Data Value \t"); scanf("%d",&data); temp = getNodeMemory(); temp->data = data; if(head == NULL){ head = temp; tail = temp; temp->next = NULL; }else{ tail->next = temp; temp->next = NULL; tail = temp; } } void display(){ struct ListNode *temp = head; while( temp != NULL ){ printf("data :%d \n",temp->data); temp = temp->next; } } void Insert(struct ListNode *head,int position){ int data,k=1; printf("Enter Data Value \t"); scanf("%d",&data); struct ListNode *temp = head,*p = NULL,*q = NULL; p = getNodeMemory(); p->data = data; if(position == 1){ p->next = temp; head = p; }else{ while( temp!=NULL && k < position ){ k++; q = temp; temp = temp->next; } q->next = p; p->next = temp; } } void insertAtEnd(struct ListNode *head){ struct ListNode *temp = head,*newNode=NULL; int data; printf("Enter Data Value \t"); scanf("%d",&data); newNode = getNodeMemory(); newNode->data = data; tail->next = newNode; tail = newNode; } void deleteNode(struct ListNode *head,int position){ struct ListNode *p,*temp = head; int k = 1; if(position == 1){ head = temp->next; free(temp); }else{ while( temp != NULL && k < position ){ p = temp; temp = temp->next; k++; } p->next = temp->next; free(temp); } } void nthNode(struct ListNode *head,int n){ struct ListNode *temp = head,*curr = head; int count = 0; while(temp){ count++; temp = temp->next; } printf("Count : %d \n",count-1); if( count-1 > n-1 ){ nthNode(head->next,n); }else{ printf("Node : %d \n",head->data); } } struct ListNode *reverse(struct ListNode *head){ struct ListNode *temp = NULL,*nextNode = NULL; while(head){ nextNode = head->next; head->next = temp; temp = head; head = nextNode; } return temp; } void palindrom(int count,struct ListNode *midNode,struct ListNode *head){ struct ListNode *temp = head,*temp1=NULL; if(head->next == NULL){ printf("List is Palindrome \n"); return; } int flag = 1; while( temp->next != midNode){ temp = head->next; } temp->next = reverse(midNode); midNode = temp->next; temp1 = midNode; while( head != midNode ){ if( head->data != temp1->data ){ flag = 0; break; } head = head->next; temp1 = temp1->next; } if(flag){ printf("List is Palindrome \n"); }else{ printf("List is not Palindrome \n"); } temp->next = reverse(midNode); } void main(){ int choice,position,count=0; struct ListNode *midNode = NULL; while(1){ printf("1.InitialInsertion\t2.NewInsertion\t3.display\t4.InsertAtEnd\t5.Delete\t6.nthNode\t7.mid\t8.exit \t"); scanf("%d",&choice); switch(choice){ case 1: create(); count++; break; case 2: printf("Enter Position \t"); scanf("%d",&position); Insert(head,position); break; case 3: display(); break; case 4: insertAtEnd(head); break; case 5: printf("Enter Position \t"); scanf("%d",&position); deleteNode(head,position); break; case 6: printf("Enter Position \t"); scanf("%d",&position); nthNode(head,position); break; case 7: midNode = mid(head); printf("C: %d\t Mid : %d\n",count,midNode->data); palindrom(count,midNode,head); break; case 8: exit(0); } } }
C
#include "types.h" #include "stat.h" #include "user.h" #include "fs.h" #define NCHILD 30 // number of children struct perf { int ctime; // process creation time int ttime; // process termination time int stime; // the time the process spent in the SLEEPING state int retime; // the time the process spent in the READY state int rutime; // the time the process spent in the RUNNING state } p; void busy_wait(){ int curr_tick = uptime(); int tick = curr_tick; int counter =0; while(counter<30){ if(uptime()!=tick){ tick = uptime(); counter++; } } exit(0); } void go_to_sleep(){ int i; for(i=0;i<30;i++) sleep(1); exit(0); } void wait_and_sleep(){ int i; int curr_tick = uptime(); int tick = curr_tick; int counter =0; for(i=0;i<5;i++){ while(counter<30){ if(uptime()!=tick){ tick = uptime(); counter++; } } sleep(1); } exit(0); } /* struct printing */ void print_performance(struct perf p ,int pid){ printf(1,"the pid is %d\n",pid ); printf(1,"the turnaround time is %d\n",(p.ttime-p.ctime)); printf(1,"the ttime is %d\n",p.ttime); printf(1,"the stime is %d\n",p.stime); printf(1,"the retime is %d\n",p.retime); printf(1,"the rutime is %d\n\n",p.rutime); } int main(int argc, char *argv[]) { printf(1,"=========== Sanity Test Results: ===========\n\n"); /*creating 10 proccesses of CPU only*/ int i; int pid; int* status=0; for(i=0;i<NCHILD/3;i++){ pid =fork(); if(pid==0) busy_wait(); } /*creating 10 proccesses of Blocking only*/ for(i=0;i<NCHILD/3;i++){ pid =fork(); if(pid==0) go_to_sleep(); } /*creating 10 proccesses of mixed */ for(i=0;i<NCHILD/3;i++){ pid =fork(); if(pid==0) wait_and_sleep(); } /* printing results and averages*/ int wait=0,turnaround=0,running=0,sleep=0;; for(i=0;i<NCHILD;i++){ // The parent collect the data from each child. int child_pid = wait_stat(status,&p); print_performance(p,child_pid); wait+=p.retime; turnaround+=(p.ttime-p.ctime); running+=p.rutime; sleep+=p.stime; } // compute averages wait=wait/NCHILD; turnaround=turnaround/NCHILD; running=running/NCHILD; sleep=sleep/NCHILD; printf(1,"=========== The avrages are ===========\n" ); printf(1,"waiting time: %d\n",wait); printf(1,"turnaround time: %d\n",turnaround); printf(1,"running time: %d\n",running); printf(1,"sleeping time: %d\n",sleep); return 1; }
C
/* * Game.h * * Contains our Game interface implementation * Each function is documented below * */ #ifndef GAME_H_ #define GAME_H_ #include "game_structs.h" /************************* NODE GETTER AND SETTER FUNCTIONS ******************************/ /* * The function gets type, x, y and returns * the value (by type) of the node in position x,y. */ int getNodeValByType(Game* gp, valType_e valType, int x, int y); /* * The function gets type, x, y, val and sets * the value (by type) of the node in position x,y. */ void setNodeValByType(Game* gp, valType_e valType, int x, int y, int val) ; /************************ GAME FUNCTIONS ***************************/ /* * Returns a pointer to a new game of size NxN (N = block_height*block_width); */ Game* initGame(int block_height, int block_width); /* * All nodes have an ISERROR boolean value. * If one of the nodes has a true ISERROR field, it is an error and the board is erroneous. * In this case the function returns 1, else 0. */ int isErroneousBoard(Game* gp); /* * Sets all values of type TEMP to 0 for all nodes. * This creates an alternative board with alternative values (currently 0). */ int clearBoardByValType(Game* gp, valType_e val_type); /* * Returned number of filled nodes in board */ int CountValuesInBoard(Game *game); /************************* ERROR HANDLING FUNCTIONS ******************************/ /* * Creates a check table for every row, col and block. * A check table is a 3D array that contains x,y values by value. * The check table is then sent to "updateErrorsFromCheckTable" * that updates the errors respectively. */ int UpdateErrors(Game *gp); /************************* FREE FUNCTIONS ******************************/ /* * Frees the actions (and all the changes within), * Frees the game board (and all nodes within), * Frees the game. */ void freeGame(Game* gp); #endif /* GAME_H_ */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_recursive.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vnafissi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/10 15:53:53 by vnafissi #+# #+# */ /* Updated: 2021/07/11 15:27:45 by vnafissi ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_createval(char **argv, int val[4][4]); int is_valid(int tab[4][4], int val[4][4], int pos); void affichage_tableau(int *tab); int ft_checkparams(int argc, char **argv); void ft_init(int tab[4][4]) { int i; int j; i = 0; j = 0; while (i < 4) { j = 0; while (j < 4) { tab[i][j] = 0; j++; } i++; } } int main(int argc, char **argv) { int val[4][4]; int tab[4][4]; if (ft_checkparams(argc, argv) == 0) { write(1, "Error\n", 6); return (0); } ft_init(val); ft_init(tab); ft_createval(argv, val); if (is_valid(tab, val, 0) == 0) { write(1, "Error\n", 6); return (0); } affichage_tableau(*tab); return (0); }
C
#include <ctype.h> #include <limits.h> #include <stdbool.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static bool print(const char* data, size_t length) { const unsigned char* bytes = (const unsigned char*) data; for (size_t i = 0; i < length; i++) { if (putchar(bytes[i]) == EOF) { return false; } } return true; } // TODO: You can only pad out to 9 characters. int printf(const char* restrict format, ...) { const int ITOA_SIZE = 16; va_list parameters; va_start(parameters, format); int written = 0; while (*format != '\0') { size_t maxrem = INT_MAX - written; if (format[0] != '%' || format[1] == '%') { if (format[0] == '%') format++; size_t amount = 1; while (format[amount] && format[amount] != '%') { amount++; } if (maxrem < amount) { // TODO: Set errno to EOVERFLOW. return -1; } if (!print(format, amount)) { return -1; } format += amount; written += amount; continue; } const char* format_begun_at = format++; if (*format == 'c') { format++; char c = (char)va_arg(parameters, int); // char promotes to int if (!maxrem) { // TODO: Set errno to EOVERFLOW. return -1; } if (!print(&c, sizeof(c))) return -1; written++; } else if ((*format == 'd') || ((*(format + 1) == 'd') && isdigit(*format)) || ((*(format + 2) == 'd') && isdigit(*(format + 1)))) { char padding = ' '; char width = 0; if (*(format + 2) == 'd') { padding = *format; format++; width = (*format) - '0'; format++; } else if (*(format + 1) == 'd') { width = (*format) - '0'; format++; } format++; // skip the 'd' int n = (int)va_arg(parameters, int); if (!maxrem) { // TODO: Set errno to EOVERFLOW. return -1; } char text[ITOA_SIZE]; itoa(n, text, 10); int len = strlen(text); if (width - len > 0) { int remainder = width - len; for (int n = 0; n < remainder; n++) { putchar(padding); } } if (!print(text, len)) { return -1; } if (len > width) { written += len; } else { written += width; } } else if (*format == 's') { format++; const char* str = va_arg(parameters, const char*); size_t len = strlen(str); if (maxrem < len) { // TODO: Set errno to EOVERFLOW. return -1; } if (!print(str, len)) return -1; written += len; } else if ((*format == 'x') || ((*(format + 1) == 'x') && isdigit(*format)) || ((*(format + 2) == 'x') && isdigit(*(format + 1)))) { char padding = ' '; char width = 0; if (*(format + 2) == 'x') { padding = *format; format++; width = (*format) - '0'; format++; } else if (*(format + 1) == 'x') { width = (*format) - '0'; format++; } format++; // skip the 'd' int n = (int)va_arg(parameters, int); if (!maxrem) { // TODO: Set errno to EOVERFLOW. return -1; } char text[ITOA_SIZE]; itoa(n, text, 16); strlwr(text); int len = strlen(text); if (width - len > 0) { int remainder = width - len; for (int n = 0; n < remainder; n++) { putchar(padding); } } if (!print(text, len)) { return -1; } if (len > width) { written += len; } else { written += width; } } else if ((*format == 'X') || ((*(format + 1) == 'X') && isdigit(*format)) || ((*(format + 2) == 'X') && isdigit(*(format + 1)))) { char padding = ' '; char width = 0; if (*(format + 2) == 'X') { padding = *format; format++; width = (*format) - '0'; format++; } else if (*(format + 1) == 'X') { width = (*format) - '0'; format++; } format++; // skip the 'd' int n = (int)va_arg(parameters, int); if (!maxrem) { // TODO: Set errno to EOVERFLOW. return -1; } char text[ITOA_SIZE]; itoa(n, text, 16); int len = strlen(text); if (width - len > 0) { int remainder = width - len; for (int n = 0; n < remainder; n++) { putchar(padding); } } if (!print(text, len)) { return -1; } if (len > width) { written += len; } else { written += width; } } else { format = format_begun_at; size_t len = strlen(format); if (maxrem < len) { // TODO: Set errno to EOVERFLOW. return -1; } if (!print(format, len)) { return -1; } written += len; format += len; } } va_end(parameters); return written; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lst_sort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lsuardi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/09 22:01:24 by lsuardi #+# #+# */ /* Updated: 2021/04/09 22:27:30 by lsuardi ### ########.fr */ /* */ /* ************************************************************************** */ #include <list.h> static void update_smallest_if_head_lower(t_list **smallest, t_list *head, t_cmpf cmp_fun) { size_t cmp_size; int cmp_ret; if ((size_t)head->size > (*smallest)->size) cmp_size = (*smallest)->size; else cmp_size = head->size; cmp_ret = (*cmp_fun)(head->data, (*smallest)->data, cmp_size); if ((cmp_ret < 0) || (!cmp_ret && (head->size < (*smallest)->size))) *smallest = head; } void lst_sort(t_list *sentinel, t_cmpf cmp_fun) { t_list *smallest; t_list *iterator; t_list *head; iterator = sentinel->next; while (iterator != sentinel) { smallest = iterator; head = iterator->next; while (head != sentinel) { update_smallest_if_head_lower(&smallest, head, cmp_fun); head = head->next; } ft_swap(&smallest->data, &iterator->data, sizeof(char *)); iterator = iterator->next; } }
C
#include <stdio.h> #include <sys/time.h> #include <stdbool.h> #include <math.h> #include "analisis_estadistico.h" #include "procesos_poisson.h" #include "gen_continuas.h" #define CANT_ITERACIONES 1000 #define TIEMPO_FUNC_SERVER 8 #define FREC_TIEMPO_ARRIBOS 4 #define FREC_TIEMPO_SERVICIO 4.2 #define CANT_CLIENT_SIMULTANEO 3 /* cantidad de clientes que puede atender el server */ /* definimos una estructura para simular un cliente, el tiempo de llegada, * el tiempo que permanece en el sistema y si realmente pudo entrar al sistema */ typedef struct { double tiempoEntrada; double tiempoSistema; /* tiempo que permanecio en el sistema */\ bool entroAlSistema; } cliente_t; /* funcion que determina la cantidad de clientes que hay en el sistema hasta * un tiempo determinado (tiempo). Toma la cantidad de clientes y verifica hasta n * clientes */ int contarClientesEnSistema(cliente_t *clientesAnteriores, int n, double tiempo) { int i = 0; double aux = 0.0; int counter = 0; for(i = 1; i < n; i++) { if(!clientesAnteriores[i].entroAlSistema) continue; aux = clientesAnteriores[i].tiempoEntrada + clientesAnteriores[i].tiempoSistema; if(aux >= tiempo) counter++; } return counter; } /* funcion que genera una simulacion del proceso, devuelve el tiempo promedio * que un cliente pasa en el sistema */ double simular_server(void) { cliente_t clientes[130]; /* por si las moscas aunque es imposible */ int i = 1; double tiemposArribos[130]; int cantTiempoArribos = 0; bool entraAlSist = false; double result = 0; double aux = 0; int counter = 0; double Muestras[130]; /* vector utilizado para guardar las Xi */ double MUempirico = 0; double ECMempirico = 0; /* calculamos los arribos */ cantTiempoArribos = process_poisson_homogeneo(TIEMPO_FUNC_SERVER, FREC_TIEMPO_ARRIBOS, tiemposArribos); /* ahora generamos para cada uno de los tiempos de arribo los clientes * y les seteamos el tiempo de servicio */ clientes[i].tiempoEntrada = tiemposArribos[i]; clientes[i].tiempoSistema = rg_gen_exp(FREC_TIEMPO_SERVICIO); entraAlSist = (contarClientesEnSistema(clientes, i, clientes[i].tiempoEntrada) <= CANT_CLIENT_SIMULTANEO); clientes[i].entroAlSistema = entraAlSist; for(i = 2; i <= cantTiempoArribos; i++) { /* veamos que en realidad va a empezar un cliente a ser atendido * cuando el otro sea liberado, ya que la atencion a los clientes * es secuencial, no paralela */ clientes[i].tiempoEntrada = tiemposArribos[i]; clientes[i].tiempoSistema = rg_gen_exp(FREC_TIEMPO_SERVICIO); /* verificamos si el tiempo de servicio del cliente anterior se * superpone con nuestra llegada y de ser asi deberiamos correr * el tiempo en el sistema */ aux = clientes[i-1].tiempoEntrada + clientes[i-1].tiempoSistema; if(aux > clientes[i].tiempoEntrada){ /* le debemos agregar el Delta time */ clientes[i].tiempoSistema += (aux - clientes[i].tiempoEntrada); } entraAlSist = (contarClientesEnSistema(clientes, i, clientes[i].tiempoEntrada) <= CANT_CLIENT_SIMULTANEO); clientes[i].entroAlSistema = entraAlSist; } /* calculamos el promedio de tiempo en el sistema de los clientes */ for(i = 1; i <= cantTiempoArribos; i++) { if(!clientes[i].entroAlSistema) continue; Muestras[counter] = clientes[i].tiempoSistema; counter++; result += clientes[i].tiempoSistema; } /*! notar que aca deberiamos calcular el error cuadratico medio por medio * de boostrap, recordando ECMempirico[X| , MUempirica] = * Sumatoria .... Sumatoria pow((g(Xi1,..,Xin) - MUempirica),2)/pow(n,n) * from i1=1 to n.... from in=1 to n * En este caso g(Xi1,..,Xin) es la media muestral X|. * Deberiamos calcular entonces MUempirica = Sumatoria Xi/n from i=1 to n * de los datos muestrales. */ for(i = 1; i < counter; i++) { MUempirico += Muestras[i]; } MUempirico /= (double)counter; ECMempirico = bootstrap_media(Muestras, counter); printf("MUEmpirico: %G\n", MUempirico); printf("ECMempirico: %G\n", ECMempirico); return (result / (double) counter); } int main8(int argc, char * argv[]) { double Xobservada = 0, Xpromj = 0, Xpromj1 = 0; double Sj = 0, Sj1 = 0; double desvEst = 0; double result = 0; double mitadLongIntervalo = 0; int n = 0; /*for(n = 1; n <= 2 ; n++){ Xobservada = simular_server(); result += Xobservada; Xpromj1 = estimar_media_muestral(n, Xpromj, Xobservada); Sj1 = estimar_varianza_muestral(n, Sj, Xpromj1, Xpromj); Xpromj = Xpromj1; Sj = Sj1; } */ /*printf("Media de tiempo de espera: %f\n", result/(double)n); printf("Valor estimado de tiempo de espera: %f\n", Xpromj1); printf("La varianza muestral = %f\n", Sj1); */ double sample[500]; for(n = 0; n < 500; n++) sample[n] = 4; for(n = 0; n < 500; n++){ Xobservada = sample[n]; Xpromj1 = estimar_media_muestral(n, Xpromj, Xobservada); Sj1 = estimar_varianza_muestral(n, Sj, Xpromj1, Xpromj); /* Actualizamos los datos antiguos */ Xpromj = Xpromj1; Sj = Sj1; } double mediaInef = estimar_media_muest_inef(sample, 500); printf("Media ineficiente : %G\t Varianza ineficiente : %G\n", mediaInef, estimar_var_muest_inef(sample,500,mediaInef)); printf("Xpromj1: %G\t Sj1: %G\n", Xpromj1, Sj1); printf("\n\n\nCALCULANDO ECM[Media] BOOSTRAP: %G\n", bootstrap_media(sample,500)); printf("\n\n\nCALCULANDO ECM[Varianza] BOOSTRAP: %G\n", bootstrap_varianza(sample,500)); return 0; }
C
#include<stdio.h> //for a power n int power(int base,int exp){ if(exp!=0){ return(base*power(base,exp-1)); } else return 1; } int main(){ int base,exp,result; printf("Enter base number and power number :\n"); scanf("%d%d",&base,&exp); result=power(base,exp); printf("%d^%d =%d\n\n",base,exp,result); }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct mensaje { long mtype; char mtext[100]; }; int main(int argc, char *argv[]) { struct mensaje buf; int msqid; key_t key; long mtype; if ( argc < 2 ) { printf(" \n\nError: El formato debe ser %s <MTYPE>\n\n",argv[0]); exit(1); } if ( (key = ftok("EscribeConID.c", 'M')) == -1) { perror ("Error en ftok"); exit (1); } if ( (msqid = msgget(key, 0644)) == -1) { perror ("Error en msgget"); exit (1); } printf ("\nCLIENTE\nDatos Recibidos:\n"); do { mtype=atoi(argv[1]); msgrcv(msqid, (struct msgbuf *)&buf, sizeof(buf), mtype, 0); printf ("%s\n",buf.mtext); } while (1) ; return 0; }
C
/*This program accesses elements of an array using the array name, *and using pointers. */ #include <stdio.h> #define NROWS 3 #define NCOLS 3 void main(){ long array[NROWS][NCOLS]={ {10L,11L,12L}, {20L,21L,22L}, {30L,31L,32L} }; long *plong=NULL; int index=0; int index2=0; /*The significance of next line is that plong is a pointer to a long * while array is a pointer to a pointer to a long. Hence, we *dereference array before assigning it to plong. * This line could also have been written as plong=&array[0][0] */ plong=*array; printf("Printing the array elements using pointer.\n"); printf("Address in decimal\tAddress in hex\tArray element\n"); for(index=0;index<NROWS*NCOLS;index++){ printf("%d\t%p\t%ld\n",(plong+index),(plong+index),*(plong+index)); } /*Notice the use of *array inside the for loop. This is an important *difference between pointer to a data-type vs array name for an array *of that data-type. Array names can have muliple levels of indirection, *so you may need to put muliple * operators before an array name, to use *it for accessing the element. */ printf("Printing the array elements using array name.\n"); printf("Address in decimal\tAddress in hex\tArray element\n"); for(index=0;index<NROWS*NCOLS;index++){ printf("%d\t%p\t%ld\n",(*array+index),(*array+index),*(*array+index)); } }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> void dumpTermios(const struct termios *t) { printf("c_iflag: %08x\n", t->c_iflag); printf("c_oflag: %08x\n", t->c_oflag); printf("c_cflag: %08x\n", t->c_cflag); printf("c_lflag: %08x\n", t->c_lflag); } void getCursor(int *x, int *y) { /* This escape sequence queries the current coordinates from the terminal. * The terminal responds on stdin */ printf("\033[6n"); scanf("\033[%d;%dR", y, x); } void getTerminalSize(int *lines, int *cols) { // save cursor position, move cursor, query position // The terminal responds on stdin printf("\033[s\033[999;999H\033[6n"); scanf("\033[%d;%dR", lines, cols); // restore cursor position printf("\033[u"); } void getTerminalResolution(int *xres, int *yres) { printf("\033[14t"); scanf("\033[4;%d;%dt", yres, xres); } int main() { struct termios saved, temp; const char *dev; int fd; int lines=24, cols=80; int xres=0, yres=0; // get tty dev = ttyname(STDIN_FILENO); if (!dev) { exit(1); } // open tty fd = open(dev, O_RDWR | O_NOCTTY); if (fd < 0) { exit(1); } // save terminal settings if (tcgetattr(fd, &saved) < 0) { exit(1); } // modify terminal settings // - turn off ICANON so input is available immediately // - turn off ECHO, otherwise the response to CSI [6n will // be displayed in the terminal // - disable receiver temp = saved; temp.c_lflag &= ~ICANON; temp.c_lflag &= ~ECHO; //temp.c_cflag &= ~CREAD; tcsetattr(fd, TCSANOW, &temp); // query cursor position getTerminalSize(&lines, &cols); getTerminalResolution(&xres, &yres); // restore terminal settings tcsetattr(fd, TCSANOW, &saved); close(fd); // print results printf("%d %d %d %d\n", lines, cols, xres, yres); exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdbool.h> #include <sys/types.h> #include <sys/stat.h> /* name is obvious*/ bool file_exists(const char* file) { if(access(file, F_OK ) != -1) { return true; } else { return false; } } /* simple function to run the tool as a deamon */ int daemonize(const char *pidfile) { pid_t process_id = 0; pid_t sid = 0; char *pid_val = NULL; size_t len = 0; FILE *fp = NULL; if (file_exists(pidfile)) { fp = fopen(pidfile, "r"); fprintf(stdout, "[-] dcsd_status is already running\n"); getline(&pid_val, &len, fp); fprintf(stdout, "[i] PID = %s\r", pid_val); fclose(fp); exit(-1); } /* create child process */ process_id = fork(); /* check if fork() failed */ if (process_id < 0) { perror("fork"); exit(1); } /* PARENT PROCESS. Let's kill it. */ if (process_id > 0) { fp = fopen(pidfile, "a+"); fprintf(stdout, "[i] PID %d\r", process_id); fprintf(fp, "%d\n",process_id); fclose(fp); /* return success in exit status */ exit(0); } /* unmask the file mode */ umask(0); /* set new session */ sid = setsid(); if(sid < 0) { exit(1); } #ifdef DEBUG fprintf(stdout, "[i] debug mode\n"); #else /* Close stdin. stdout and stderr */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); #endif return 0; } int get_instance_pid(const char *file) { FILE *fp = NULL; char *pid_val = NULL; size_t len = 0; fp = fopen(file, "r"); /* check if we can access file */ if (fp == NULL) { fprintf(stderr, "[e] could not open %s\n", file); return -1; } /* get the first line of the file which is PID */ getline(&pid_val, &len, fp); fclose(fp); /* return PID of server */ return atoi(pid_val); }
C
#include "usertraps.h" #include "misc.h" #include "producer.h" void main (int argc, char *argv[]) { //uint32 h_mem; // Handle to the shared memory page sem_t s_procs_completed; // Semaphore to signal the original process that we're done //init the semaphores unsigned int h_mem; molecules *mol; //init the message in the mbox char message[2]; if (argc != 3) { Printf("Usage: "); Printf(argv[0]); Printf(" <handle_to_shared_memory_page> <handle_to_page_mapped_semaphore>\n"); Exit(); } s_procs_completed = dstrtol(argv[1], NULL, 10); h_mem = dstrtol(argv[2], NULL, 10); //map mol = (molecules *) shmat(h_mem); if(mol == NULL){ Printf("Map failed in SO injection \n"); Exit(); } //open the mailbox if(mbox_open(mol->s2_mbox) != MBOX_SUCCESS){ Printf("Open the mailbox failed, check the condition"); Exit(); } //reaction here, consume mbox_recv(mol->s2_mbox, 2, (void *)message); //close the mailbox after it finished if(mbox_close(mol->s2_mbox) != MBOX_SUCCESS){ Printf("Close the mailbox failed, check the condition"); Exit(); } if(mbox_open(mol->s_mbox) != MBOX_SUCCESS){ Printf("Open the mailbox failed, check the condition"); Exit(); } //produce the twos mbox_send(mol->s_mbox, 1, (void *) "S"); mbox_send(mol->s_mbox, 1, (void *) "S"); if(mbox_close(mol->s_mbox) != MBOX_SUCCESS){ Printf("Close the mailbox failed, check the condition"); Exit(); } Printf("S2 -> S + S reacted, PID: %d\n", getpid()); if(sem_signal(s_procs_completed) != SYNC_SUCCESS) { Printf("Bad semaphore s_procs_completed (%d) in ", s_procs_completed); Printf(argv[0]); Printf(", exiting...\n"); Exit(); } }
C
#include <stdio.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int argc, char* argv[]) { int sockfd; struct sockaddr_in server_addr; struct sockaddr_in client_addr; int sin_size, iDataNum; char buffer[4096]; int portnumber = 8080; if(argc != 2) { fprintf(stderr, "Usage:%s portnumber\a\n", argv[0]); return 0; } //设置端口 if((portnumber = atoi(argv[1])) < 0) { fprintf(stderr, "Usage:%s portnumber\a\n", argv[0]); return 0; } //AF_INET(TCP/IP – IPv4) //SOCK_DGRAM(UDP数据报) if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "Socket error:%s\n\a", strerror(errno)); return 0; } bzero(&server_addr, sizeof(struct sockaddr_in)); //字符清零 server_addr.sin_family = AF_INET; //地址类型 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); //IP地址 server_addr.sin_port = htons(portnumber); //端口号 //将套接字与指定端口相连 if(bind(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1) { fprintf(stderr,"Bind error:%s\n\a",strerror(errno)); return 0; } sin_size = sizeof(struct sockaddr_in); while(1) { iDataNum = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &sin_size); fprintf(stdout,"Server get connection from %s\n",inet_ntoa(client_addr.sin_addr)); if(iDataNum < 0) { perror("Recv\n"); return 0; } printf("Recv data is %s\n", buffer); sendto(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, sizeof(client_addr)); } close(sockfd); return 0; }
C
#include <stdio.h> #include <time.h> #include <string.h> #include <stdlib.h> typedef struct _Book{ int book_id; //도서번호 char *book_name; //도서명 char *purblisher; //출판사 char *writer; //저자명 long isbn; //ISBN char *local; //소장처 char book_rent; //대여가능 여부 struct _Book *next; //자기참조 }Book; typedef struct _Client{ int std_id; //학번 char *password; //비밀번호 char *std_name; //학생 이름 char *addr; //주소 char *ph_num; //핸드폰 번호 struct _Client *next; } Client; typedef struct _Borrow{ int std_id; //학번 int bk_id; //도서번호 time_t rent_date; //빌린 날짜 time_t return_date; //반납 날짜 struct _Borrow *next; } Borrow; /*-------------영민,민영-------------*/ typedef struct _client { int std_id; //학번 char password[300]; //비밀번호 char std_name[300]; //이름 char addr[300]; //주소 char ph_num[300]; //연락처 struct _client* next; }client; /*-------------영민,민영-------------*/ /*----------------용준-----------------*/ typedef struct book { char bnum[8];//책번호 char bname[100];//책이름 char pname[100];//출판사이름 char writer[100];//저자명 char ISBN[15];//ISBN번호 char own[100];//소장처 char YN;//Y or N 대여가능여부 struct book *next; } book;//book.txt파일에서 책 정보 읽어오는 자기참조구조체선언 /*-----------------용준----------------*/ void login(Book *cur, Client *cl_cur, Borrow *br_cur); int admin_login(Book *cur, Client *cl_cur, Borrow *br_cur); //로그인 함수 void book_manage(int num, Book *cur, Client *cl_cur, Borrow *br_cur); char *get_string(char * str, int start); Book *create_node(Book *data); void insert_node(Book **cur, Book *new_node); void add_node(Book **cur, Book *new_node, Book *next_node); void delete_node(Book **cur, Book *del_node); Book *book_regis(Book **cur); Borrow *create_br_node(Borrow *data); void insert_br_node(Borrow **cur, Borrow *new_node); void delete_br_node(Borrow **cur, Borrow *del_node); Client *create_cl_node(Client *data); void insert_cl_node(Client **cur, Client *new_node); void delete_cl_node(Client **cur, Client *del_node); time_t make_time (time_t date, int *year, int *month, int *day); void mul_time(time_t date, int *year, int *month, int *day); /*-------------영민-------------*/ void client_add(); void register_member(); // 회원 등록 void member_menu(int id, Borrow *br_cur, Book *bk_cur, Client *cl_cur); // 회원 메뉴 void modify_member(); // 회원 정보 수정 void delete_member(int id, Borrow *br_cur, Client *cl_cur); // 회원 탈퇴 void borrow_search(int id, Borrow *br_cur, Book *bk_cur); client *client_head; client *client_tail; char id_login[300]; // 로그인할때 쓸 학번 char password_login[50]; // 로그인할때 쓸 비밀번호 /*-------------영민-------------*/ /*-------------민영-------------*/ void search_name(FILE *); //이름 검색 함수 void all_client(FILE *); //전체검색 void client_list(); //전채검색 void search_id_num(FILE *); //학번검색 /*-------------민영-------------*/ /*-------------용준-------------*/ typedef book *LINK;//struct book *형을 LINK정의. void findbname(FILE *);//책이름검색함수 void findpname(FILE *, char *);//출판사명검색함수 void findISBN(FILE *);//ISBN검색함수 void findwriter(FILE *, char *);//작가명검색함수 void findall(FILE *);//전체검색함수 void search();//회원 로그인 후 도서검색 눌렀을때 실행 /*-------------용준-------------*/ FILE *fp,*bfp,*cfp,*dfp,*ifp; int main (void) { /*-------------영민-------------*/ client_head=(client *)malloc(sizeof(client)); client_tail=(client *)malloc(sizeof(client)); client_add(); /*-------------영민-------------*/ bfp = fopen("./borrow.txt","r+w"); if(bfp == NULL) printf("파일없음\n"); Borrow *br_p = (Borrow*)malloc(sizeof(Borrow)); Borrow *br_head = (Borrow*)malloc(sizeof(Borrow)); Borrow *br_cur = br_head; br_head->next = NULL; br_head->std_id=0; char *br_info = (char *)malloc(1024); int br_curNum=0; while(fgets(br_info,1024,bfp) != NULL) { //구조체에 데이터 파싱 br_curNum=0; br_p->std_id = atoi(get_string(br_info,br_curNum)); br_curNum += 9; br_p->bk_id = atoi(get_string(br_info,br_curNum)); br_curNum += strlen(get_string(br_info,br_curNum))+1; br_p->rent_date = atoi(get_string(br_info,br_curNum)); br_curNum += strlen(get_string(br_info,br_curNum))+1; br_p->return_date = atoi(get_string(br_info,br_curNum)); insert_br_node(&br_cur,create_br_node(br_p)); } br_cur = br_head; cfp = fopen("./client.txt","r+w"); if(cfp == NULL) printf("파일없음\n"); Client *cl_p = (Client*)malloc(sizeof(Client)); Client *cl_head = (Client*)malloc(sizeof(Client)); Client *cl_cur = cl_head; cl_head->next = NULL; cl_head->std_id = 0; char *cl_info = (char *)malloc(1024); int cl_curNum = 0; while(fgets(cl_info,1024,cfp) != NULL) { cl_curNum = 0; cl_p->std_id = atoi(get_string(cl_info,cl_curNum)); cl_curNum += 9; cl_p->password = get_string(cl_info,cl_curNum); cl_curNum += strlen(cl_p->password)+1; cl_p->std_name = get_string(cl_info,cl_curNum); cl_curNum += strlen(cl_p->std_name)+1; cl_p->addr = get_string(cl_info,cl_curNum); cl_curNum += strlen(cl_p->addr)+1; cl_p->ph_num = get_string(cl_info,cl_curNum); cl_curNum += strlen(cl_p->ph_num)+1; insert_cl_node(&cl_cur,create_cl_node(cl_p)); } cl_cur = cl_head; /* 링크드리스트 */ fp = fopen("./book.txt","r+w"); if(fp == NULL) printf("파일 없음\n"); Book *book_p=(Book*)malloc(sizeof(Book)); Book *bk_head = (Book *)malloc(sizeof(Book)); Book *cur = bk_head; bk_head->next = NULL; bk_head -> book_id = 0; char *info = (char *)malloc(1024); int curNum=0; while(fgets(info, 1024, fp) != NULL) { //구조체에 데이터 파싱 curNum=0; book_p->book_id = atoi(get_string(info, curNum)); curNum += sizeof(book_p->book_id)*2; book_p->book_name=get_string(info,curNum); curNum += strlen(book_p->book_name)+1; book_p->purblisher=get_string(info, curNum); curNum += strlen(book_p->purblisher)+1; book_p->writer=get_string(info, curNum); curNum += strlen(book_p->writer)+1; book_p->isbn = atol(get_string(info, curNum)); curNum += sizeof(book_p->isbn)+6; book_p->local=get_string(info, curNum); curNum += strlen(book_p->local)+1; char *rent=get_string(info, curNum); book_p->book_rent=rent[0]; curNum += 1; insert_node(&cur, create_node(book_p)); } cur= bk_head; /* 메인화면 */ int select; system("clear"); while(1) { system("clear"); printf(">>도서관 서비스<<\n"); printf("1. 회원가입\t2.로그인\t3. 프로그램종료\n"); printf("번호를 선택하세요: "); scanf("%d", &select); if(select == 1) { //회원가입 함수 /*-------------영민-------------*/ register_member(); /*-------------영민-------------*/ } else if(select == 2) { //로그인함수 system("clear"); login(cur, cl_cur, br_cur); } else if(select == 3) { /*-------------영민-------------*/ printf("====================================\n"); printf("프로그램을 종료합니다\n"); exit(1); /*-------------영민-------------*/ } } fclose(fp); fclose(bfp); fclose(cfp); return 0; } void login(Book *cur, Client *cl_cur, Borrow *br_cur) { while(1) { printf(">>로그인<<\n"); printf("학번: "); scanf("%s", id_login); if (!strcmp(id_login, "admin")) { printf("비밀번호: "); scanf("%s", password_login); if (!strcmp(password_login, "lib_admin7")) { admin_login(cur, cl_cur, br_cur); //관리자용 메뉴로 이동 break; } else { printf("비밀번호가 틀렸습니다. 다시입력하십시오.\n"); id_login[0] = '\0'; password_login[0] = '\0'; continue; //로그인 화면 처음으로 이동 } } else { client* current = (client*)malloc(sizeof(client)); current = client_head; while (current != client_tail) { if (current->std_id == atoi(id_login)) //입력한 학번이 존재할 때 { printf("비밀번호: "); scanf("%s", password_login); if (!strcmp(current->password, password_login)) //비밀번호가 맞으면 회원용 메뉴로 이동 { member_menu(atoi(id_login), br_cur, cur, cl_cur); break; } else //아니면 반복문 나온후 로그인 화면 처음으로 이동 { printf("비밀번호가 틀렸습니다. 다시 입력하세요.\n"); password_login[0] = '\0'; break; } } current = current->next; } if (current == client_tail) //linked_list를 전부 확인해도 입력한 학번이 없을 때 { printf("존재하지 않는 학번입니다. 다시 입력하세요.\n"); continue; //로그인 화면으로 이동 } if (!strcmp(current->password, password_login)) //회원용 메뉴를 나오면 로그인 화면종료 break; //비밀번호가 다를경우 로그인화면 으로 이동 } } } int admin_login(Book *cur, Client *cl_cur, Borrow *br_cur) { system("clear"); int num; printf(">> 관리자 메뉴 <<\n"); printf("1. 도서 등록 2. 도서 삭제\n"); printf("3. 도서 대여 4. 도서 반납\n"); printf("5. 도서 검색 6. 회원 목록\n"); printf("7. 로그아웃 8. 프로그램 종료\n"); printf("번호를 선택하세요 : "); scanf("%d", &num); if(num == 1 || num == 2 || num == 3 || num == 4 || num == 5) book_manage(num,cur,cl_cur,br_cur); else if(num == 6) { /*------------민영----------*/ client_list(); //회원 목록 admin_login(cur, cl_cur, br_cur); } else if (num == 7) { //로그아웃 return 0; } else if (num == 8) { exit(0); } return 0; } void book_manage(int num, Book *cur, Client *cl_cur, Borrow *br_cur) { int del_num=0,rent_num=0; system("clear"); switch(num) { case 1 : //도서 등록 //isbn순으로 정렬 { Book *tail, *corr_cur; Book *bk_head = cur; printf(">>도서 등록<<\n"); tail = book_regis(&cur); //마지막 번호 받아옴 fflush(stdout); cur = bk_head->next; while (cur != NULL) { if(cur->isbn > tail->isbn && cur->isbn != tail->isbn){ //기존isbn보다 tail isbn 작은거 찾기 corr_cur=cur; //위치 저장 break; } if(cur->isbn == tail->isbn) { //기존이랑 tail isbn과 같다면 corr_cur=cur; //위치 저장 break; } if(cur->next ==NULL) { //맨마지막이면 corr_cur=cur; break; } cur = cur->next; } cur = bk_head; //head값 저장 FILE *fp = fopen("book.txt", "w"); fflush(stdout); Book *last_node; //마지막노드위치 if(cur->next->isbn > tail->isbn){ //처음꺼 fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",tail->book_id, tail->book_name, tail->purblisher, tail->writer, tail->isbn, tail->local, tail->book_rent); add_node(&cur,create_node(tail), cur->next); cur = bk_head->next->next; while(cur != NULL) { fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); cur=cur->next; } cur=bk_head->next; } else if (cur->next->isbn <= tail->isbn) { //중간이면 cur=bk_head->next; while(cur != NULL) { //마지막찾기 last_node = cur; cur=cur->next; } cur=bk_head->next; if(last_node->isbn >= tail->isbn) { while(cur != NULL) { fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); if(cur->next == corr_cur) break; cur = cur->next; } fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",tail->book_id, tail->book_name, tail->purblisher, tail->writer, tail->isbn, tail->local, tail->book_rent); Book *next_node = cur->next; add_node(&cur,create_node(tail), next_node); cur = cur->next; while(cur != NULL) { fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); cur = cur->next; } cur = bk_head; } } while(cur != NULL) { //마지막꺼찾기 last_node = cur; cur=cur->next; } cur=bk_head->next; if(last_node->isbn < tail->isbn) { while(cur != NULL) { fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); if(cur->next == NULL) break; cur=cur->next; } fprintf(fp, "%d|%s|%s|%s|%ld|%s|%c\n",tail->book_id, tail->book_name, tail->purblisher, tail->writer, tail->isbn, tail->local, tail->book_rent); insert_node(&cur,create_node(tail)); cur = bk_head; } fclose(fp); break; } case 2 : // 도서 삭제 { printf(">>도서 삭제<<\n"); printf("1. 도서명 검색 2. ISBN 검색\n"); printf("\n\n검색 번호를 입력하세요 : "); scanf("%d",&del_num); Book *head=cur; //head위치 저장포인터 Book *corr_cur=cur; //null이 아님을 피하기위해 초기화 Book *del_node; //지울 노드 전번째 노드위치 포인터 int null_check = 0, del_id = 0; //도서이름이 있는지 확인변수, 삭제할 도서번호 if(del_num == 1) { char b_name[100]=""; //도서 이름입력변수 printf("도서명을 입력하세요 : "); getchar(); scanf("%[^\n]", b_name); fflush(stdout); cur=head->next; while(cur != NULL) { //찾는 도서이름이 없는지 확인 if(!strcmp(cur->book_name, b_name)) //도서이름이 있으면 null_check ++; cur=cur->next; } if(null_check == 0) corr_cur = NULL; //도서이름이 없으면 cur = head->next; if(corr_cur != NULL) { //찾는 도서이름이 있으면 printf("도서 번호 :"); while(cur != NULL) { if(!strcmp(cur->book_name,b_name)){ printf(" %d(삭제 가능 여부 : %c)",cur->book_id, cur->book_rent); corr_cur = cur; // 도서위치저장 } cur=cur->next; } printf("\n도서명 : %s\n",corr_cur->book_name); printf("출판사 : %s\n", corr_cur->purblisher); printf("저자명 : %s\n", corr_cur->writer); printf("ISBN : %ld\n", corr_cur->isbn); printf("소장처 : %s\n", corr_cur->local); printf("\n삭제할 도서의 번호를 입력하세요 : "); scanf("%d", &del_id); cur=head->next; //cur위치는 다시 처음으로 int check=0,success=0; while(cur != NULL) { if(!strcmp(cur->book_name,b_name) && cur->book_id == del_id) { check++; corr_cur=cur; //지울노드에 현재커서위치 넘겨주기 if(cur->book_rent=='N') { printf("이 도서는 삭제할 수 없습니다.\n"); } else if (cur->book_rent=='Y') { success = 1; printf("도서를 삭제했습니다.\n"); } } cur = cur->next; } cur = head; while(cur != NULL) { if(cur->next == corr_cur) { del_node = cur; //지울노드 전노드 위치 넘겨주기 } cur=cur->next; } cur=head; //cur위치 다시 처음으로 FILE *dfp; if(success==1) { delete_node(&del_node,corr_cur); dfp = fopen("./book.txt","w"); while(cur!=NULL) { if(cur->book_id != 0) { fprintf(dfp, "%d|%s|%s|%s|%ld|%s|%c\n", cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); } cur=cur->next; } cur = head->next; } else { //예외 처리 dfp = fopen("./book.txt","r"); } fclose(dfp); if(check == 0) printf("도서 번호가 잘못되었습니다.\n"); } else if (corr_cur == NULL) { printf("찾으시는 도서이름이 없습니다.\n"); } } else if (del_num == 2) { long b_isbn; Book *del_node; //지울 노드 전번째 노드위치 포인터 printf("ISBN을 입력하세요 : "); scanf("%ld", &b_isbn); while(cur != NULL) { if(cur->isbn == b_isbn) //찾는 도서 isbn이 있으면 null_check ++; cur=cur->next; } if(null_check == 0) corr_cur = NULL; //도서이름이 없으면 cur = head->next; if(corr_cur != NULL) { //있을때 printf("도서 번호 :"); while(cur != NULL) { if(cur->isbn == b_isbn) { printf(" %d(삭제 가능 여부: %c)", cur->book_id, cur->book_rent); corr_cur = cur; //도서위치저장 } cur=cur->next; } printf("\n도서명 : %s\n",corr_cur->book_name); printf("출판사 : %s\n", corr_cur->purblisher); printf("저자명 : %s\n", corr_cur->writer); printf("ISBN : %ld\n", corr_cur->isbn); printf("소장처 : %s\n", corr_cur->local); printf("\n삭제할 도서의 번호를 입력하세요 : "); scanf("%d", &del_id); cur=head->next; //cur위치는 다시 처음으로 int check=0,success=0; while(cur != NULL) { if(cur->isbn == b_isbn && cur->book_id == del_id) { check++; corr_cur=cur; //지울노드에 현재커서위치 넘겨주기 if(cur->book_rent=='N') { printf("이 도서는 삭제할 수 없습니다.\n"); } else if (cur->book_rent=='Y') { success = 1; printf("도서를 삭제했습니다.\n"); break; } } cur = cur->next; } cur=head; while(cur != NULL) { if(cur->next == corr_cur) { del_node = cur; //지울노드 전노드 위치 넘겨주기 } cur=cur->next; } cur=head; //cur위치 다시 처음으로 FILE *dfp; if(success==1) { delete_node(&del_node,corr_cur); dfp = fopen("./book.txt","w"); while(cur!=NULL) { if(cur->book_id!=0) { fprintf(dfp, "%d|%s|%s|%s|%ld|%s|%c\n", cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); } cur=cur->next; } } else { //예외 처리 dfp = fopen("./book.txt","r"); } fclose(dfp); if(check == 0) printf("도서 번호가 잘못되었습니다.\n"); } else if(corr_cur == NULL) { //없을때 printf("찾으시는 도서ISBN이 없습니다.\n"); } } else { //1,2번 아닌거 입력했을때 printf("번호를 잘못 입력하셨습니다.\n"); } break; } case 3 : { //도서 대여 printf(">>도서 대여<<\n"); printf("1. 도서명 검색 2. ISBN 검색\n"); printf("\n\n검색 번호를 입력하세요 : "); scanf("%d", &rent_num); Borrow *br_head=br_cur; Book *bk_head=cur; Client *cl_head=cl_cur; Book *cor_cur=cur; //null이 아님을 피하기 위해 초기화 int n_check=0; if(rent_num == 1){ char b_name[100]="",rent='\0'; int s_id=0,b_id=0; getchar(); printf("도서명을 입력하세요 : "); scanf("%[^\n]", b_name); cur= bk_head->next; while(cur != NULL) { if(!strcmp(cur->book_name, b_name)) //도서이름이 있으면 n_check ++; cur=cur->next; } if(n_check == 0) cor_cur = NULL; //도서이름이 없으면 cur = bk_head->next; if(cor_cur != NULL) { //찾는 도서이름이 있으면 printf("도서 번호 :"); while(cur != NULL) { if(!strcmp(cur->book_name,b_name)){ printf(" %d(대여 가능 여부 : %c)",cur->book_id, cur->book_rent); cor_cur = cur; // 도서위치저장 } cur=cur->next; } printf("\n도서명 : %s\n",cor_cur->book_name); printf("출판사 : %s\n", cor_cur->purblisher); printf("저자명 : %s\n", cor_cur->writer); printf("ISBN : %ld\n", cor_cur->isbn); printf("소장처 : %s\n", cor_cur->local); printf("\n학번을 입력하세요 : "); scanf("%d", &s_id); cur=bk_head->next; int id_check=0,id_suc=0; while(cl_cur != NULL) { if(s_id == cl_cur->std_id) //같으면 id_check = 1; cl_cur=cl_cur->next; } cl_cur = cl_head->next;//처음으로 if(id_check == 0) { printf("학번이 잘못되었습니다.\n"); break; } printf("도서번호를 입력하세요 : "); scanf("%d", &b_id); while(cur != NULL) { if(b_id == cur->book_id) { id_suc=1; cor_cur = cur; //현재위치 잡아주기 } cur=cur->next; } cur = bk_head->next; printf("이 도서를 대여합니까? : "); getchar(); scanf("%c", &rent); FILE *br_fp; struct tm *t; time_t timer; char *weekday[] = {"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"}; char *a_date=(char*)malloc(100); char *b_date=(char*)malloc(100); time(&timer); t = localtime(&timer); mktime(t); if(id_suc==1 && rent == 'Y' && cor_cur->book_rent == 'Y') { printf("도서가 대여 되었습니다.\n"); cor_cur->book_rent = 'N'; br_fp = fopen("./borrow.txt","a+w"); sprintf(a_date, "%d%02d%02d",t->tm_year+1900, t->tm_mon+1, t->tm_mday); timer += 60*60*24*30; t = localtime(&timer); mktime(t); if(!strcmp(weekday[t->tm_wday],"일요일")){ timer += 60*60*24; t=localtime(&timer); mktime(t); } sprintf(b_date, "%d%02d%02d",t->tm_year+1900, t->tm_mon+1, t->tm_mday); fprintf(br_fp,"%d|%d|%s|%s\n", s_id, b_id, a_date, b_date); fclose(br_fp); bfp=fopen("./book.txt","wt"); while(cur != NULL) { if(cur->book_id==cor_cur->book_id){ //부분수정 fprintf(bfp, "%d|%s|%s|%s|%ld|%s|%c\n", cor_cur->book_id, cor_cur->book_name, cor_cur->purblisher,cor_cur->writer, cor_cur->isbn, cor_cur->local, cor_cur->book_rent); } else { fprintf(bfp, "%d|%s|%s|%s|%ld|%s|%c\n", cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); } cur=cur->next; } fclose(bfp); } else if(id_suc==1 && rent == 'Y' && cor_cur->book_rent == 'N') { printf("도서 대여를 실패했습니다.\n"); } else if (rent == 'N') { printf("도서 대여를 취소합니다. \n"); } free(a_date); free(b_date); } else if(cor_cur == NULL) { printf("찾으시는 도서이름이 없습니다.\n"); } } else if (rent_num == 2) { //isbn검색 long b_isbn; char rent='\0'; int s_id=0,b_id=0; printf("ISBN을 입력하세요 : "); scanf("%ld", &b_isbn); while(cur != NULL) { if(cur->isbn == b_isbn) //찾는 도서 isbn이 있으면 n_check ++; cur=cur->next; } if(n_check == 0) cor_cur = NULL; //도서 isbn이 없으면 cur = bk_head->next; if(cor_cur != NULL) { //찾는 도서isbn이 있으면 printf("도서 번호 :"); while(cur != NULL) { if(cur->isbn == b_isbn) { printf(" %d(대여 가능 여부 : %c)",cur->book_id, cur->book_rent); cor_cur = cur; // 도서위치저장 } cur=cur->next; } printf("\n도서명 : %s\n",cor_cur->book_name); printf("출판사 : %s\n", cor_cur->purblisher); printf("저자명 : %s\n", cor_cur->writer); printf("ISBN : %ld\n", cor_cur->isbn); printf("소장처 : %s\n", cor_cur->local); printf("\n학번을 입력하세요 : "); scanf("%d", &s_id); cur=bk_head->next; int id_check=0,id_suc=0; while(cl_cur != NULL) { if(s_id == cl_cur->std_id) //같으면 id_check = 1; cl_cur=cl_cur->next; } cl_cur = cl_head->next;//처음으로 if(id_check == 0) { printf("학번이 잘못되었습니다.\n"); break; } printf("도서번호를 입력하세요 : "); scanf("%d", &b_id); while(cur != NULL) { if(b_id == cur->book_id) { id_suc=1; cor_cur = cur; //현재위치 잡아주기 } cur=cur->next; } cur = bk_head->next; printf("이 도서를 대여합니까? : "); getchar(); scanf("%c", &rent); FILE *br_fp; struct tm *t; time_t timer; char *weekday[] = {"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"}; char *a_date=(char*)malloc(100); char *b_date=(char*)malloc(100); time(&timer); //시간받아오는거 t = localtime(&timer); //시간 나눠주는거 mktime(t); //요일 if(id_suc==1 && rent == 'Y' && cor_cur->book_rent == 'Y') { printf("도서가 대여 되었습니다.\n"); cor_cur->book_rent = 'N'; br_fp = fopen("./borrow.txt","a+w"); sprintf(a_date, "%d%02d%02d",t->tm_year+1900, t->tm_mon+1, t->tm_mday); timer += 60*60*24*30; t = localtime(&timer); mktime(t); if(!strcmp(weekday[t->tm_wday],"일요일")){ timer += 60*60*24; t=localtime(&timer); mktime(t); } sprintf(b_date, "%d%02d%02d",t->tm_year+1900, t->tm_mon+1, t->tm_mday); fprintf(br_fp,"%d|%d|%s|%s\n", s_id, b_id, a_date, b_date); fclose(br_fp); bfp=fopen("./book.txt","wt"); while(cur != NULL) { if(cur->book_id==cor_cur->book_id){ fprintf(bfp, "%d|%s|%s|%s|%ld|%s|%c\n", cor_cur->book_id, cor_cur->book_name, cor_cur->purblisher,cor_cur->writer, cor_cur->isbn, cor_cur->local, cor_cur->book_rent); } else { fprintf(bfp, "%d|%s|%s|%s|%ld|%s|%c\n", cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); } cur=cur->next; } fclose(bfp); } else if(id_suc==1 && rent == 'Y' && cor_cur->book_rent == 'N') { printf("도서 대여를 실패했습니다.\n"); } else if (rent == 'N') { printf("도서 대여를 취소합니다. \n"); } free(a_date); free(b_date); } else if(cor_cur == NULL) { printf("찾으시는 도서가 없습니다.\n"); } } else { printf("번호를 잘못 입력하셨습니다.\n"); } break; } case 4 : { //도서 반납 int s_id=0, bk_id=0, success=0; int year, month, day; Borrow *br_head=br_cur; Book *bk_head=cur; Client *cl_head=cl_cur; Borrow *del_node,*corr_cur; char rent='\0'; printf("학번을 입력하세요 : "); scanf("%d", &s_id); struct tm* timeinfo; char *weekday[] = {"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"}; printf(">>회원의 대여 목록<<\n"); br_cur = br_head->next; while(br_cur != NULL) { if(br_cur->std_id == s_id) { bk_id = br_cur->bk_id; printf("도서번호 : %d\n", bk_id); while(cur != NULL) { if(cur->book_id == bk_id) printf("도서명 : %s\n", cur->book_name); cur=cur->next; } cur = bk_head->next; mul_time(br_cur->rent_date, &year, &month, &day); time_t baseTime = make_time(br_cur->rent_date, &year, &month, &day); timeinfo = localtime(&baseTime); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day; mktime(timeinfo); printf("대여 일자 : %ld%s\n",br_cur->rent_date,weekday[timeinfo->tm_wday]); mul_time(br_cur->return_date, &year, &month, &day); baseTime = make_time(br_cur->return_date, &year, &month, &day); timeinfo = localtime(&baseTime); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day; mktime(timeinfo); printf("반납 일자 : %ld%s\n\n",br_cur->return_date,weekday[timeinfo->tm_wday]); } br_cur=br_cur->next; } printf("반납할 도서번호를 입력하세요 : "); scanf("%d",&bk_id); printf("\n도서 반납처리를 할까요? : "); getchar(); scanf("%c",&rent); corr_cur = br_head; br_cur=br_head->next; if(rent == 'Y') { while (br_cur != NULL) { if(br_cur->bk_id == bk_id) { break; } corr_cur = br_cur; //지울 노드 찾기 br_cur = br_cur->next; } delete_br_node(&corr_cur, br_cur); } else { printf("반납처리를 취소합니다. \n"); } br_cur = br_head->next; if(rent == 'Y') { FILE *fp = fopen("./borrow.txt", "wt"); while(br_cur != NULL) { //borrow파일 수정 fprintf(fp, "%d|%d|%ld|%ld\n",br_cur->std_id,br_cur->bk_id,br_cur->rent_date,br_cur->return_date); br_cur = br_cur->next; } br_cur = br_head->next; FILE *bfp = fopen("./book.txt", "wt"); while(cur != NULL) { //book파일 수정 if(cur->book_id==bk_id){ cur->book_rent = rent; fprintf(bfp, "%d|%s|%s|%s|%ld|%s|%c\n", cur->book_id, cur->book_name, cur->purblisher,cur->writer, cur->isbn, cur->local, cur->book_rent); } else { fprintf(bfp, "%d|%s|%s|%s|%ld|%s|%c\n", cur->book_id, cur->book_name, cur->purblisher, cur->writer, cur->isbn, cur->local, cur->book_rent); } cur=cur->next; } cur=bk_head->next; fclose(fp); fclose(bfp); } break; } case 5 : {search();//도서 검색 admin_login(cur, cl_cur, br_cur); break; }} } /*-----------------------민영-------------------------*/ void client_list() { FILE *dfp = NULL; //client 파일을 여는 파일 포인터 선언 dfp = fopen("client.txt", "r"); if (dfp == NULL) { return; } int choice; char name[10]; //입력받을 이름 printf(">>검색 결과<<\n"); printf("1.이름 검색\t 2.학번 검색\n3.전체 검색\t 4.이전 메뉴\n"); printf("번호를 입력하세요\n"); scanf("%d", &choice); switch (choice) { case 1: search_name(dfp); printf("\n\n"); client_list(); break; case 2: search_id_num(dfp); printf("\n\n"); client_list(); break; case 3: { all_client(dfp); printf("\n\n"); client_list(); } break; case 4: fclose(dfp); break; default: printf("1~4사이 숫자를 입력하세요"); break; } fclose(dfp); return; } void search_name(FILE *dfp) //이름 검색 함수 { char input_name[20]; char buf[10]; client *head = NULL; client *p = NULL; client *q = (client *)malloc(sizeof(client)); printf("이름을 입력하세요:"); scanf("%s", input_name); while (1) { if (fscanf(dfp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^\n]\n", buf, q->password, q->std_name, q->addr, q->ph_num) != 5) { printf("검색 결과 없음"); break; } q->std_id = atoi(buf); if (strcmp(input_name, q->std_name) != 0) { continue; } else { printf("학번:%d\n이름:%s\n주소:%s\n전화번호:%s\n", q->std_id, q->std_name, q->addr, q->ph_num); break; } } } void search_id_num(FILE *dfp) //학번검색함수 { int input_id; char buf[10]; client *head = NULL; client *q = NULL; client *p = NULL; q = (client *)malloc(sizeof(client)); printf("학번을 입력하세요:"); scanf("%d", &input_id); while (1) { if (fscanf(dfp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^\n]\n", buf, q->password, q->std_name, q->addr, q->ph_num) != 5) { printf("검색결과가 없습니다."); break; } q->std_id = atoi(buf); if (input_id == q->std_id) { printf("\n학번:%d\n이름:%s\n주소:%s\n전화번호:%s", q->std_id, q->std_name, q->addr, q->ph_num); break; } } } void all_client(FILE *dfp) //전체 검색함수 { int count = 0; client *head = NULL; client *p = NULL; client *q = NULL; char buf[10]; while (1) { q = malloc(sizeof(client)); q->next = NULL; if (head == NULL) { head = q; if (fscanf(dfp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^\n]\n", buf, q->password, q->std_name, q->addr, q->ph_num) == 5) { q->std_id = atoi(buf); printf("학번:%d\n", q->std_id); printf("이름:%s\n", q->std_name); printf("주소:%s\n", q->addr); printf("전화번호:%s\n\n", q->ph_num); } } else { p = head; while (p->next != NULL) { p = p->next; } p->next = q; if (fscanf(dfp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^\n]\n", buf, q->password, q->std_name, q->addr, q->ph_num) == 5) { q->std_id = atoi(buf); printf("학번:%d\n", q->std_id); printf("이름:%s\n", q->std_name); printf("주소:%s\n", q->addr); printf("전화번호:%s\n\n", q->ph_num); } else { free(q); return; } } } } /*----------------------민영--------------------*/ time_t make_time (time_t date, int *year, int *month, int *day) { char* weekday[] = {"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"}; struct tm t = {0}; t.tm_year = *year - 1900; t.tm_mon = *month - 1; t.tm_mday = *day; return mktime(&t); } void mul_time(time_t date, int *year, int *month, int *day) { *year= date / 10000 ; *month = (date - ((*year) * 10000)) / 100; *day = date % 100 ; } Client *create_cl_node(Client *data) { Client *new_node = (Client*)malloc(sizeof(Client)); memcpy(new_node, data, sizeof(Client)); new_node->next = NULL; return new_node; } void insert_cl_node(Client **cur, Client *new_node) { (*cur)->next = new_node; *cur = new_node; } void delete_cl_node(Client **cur, Client *del_node) { (*cur)->next = del_node->next; free(del_node); } Borrow *create_br_node(Borrow *data) { Borrow *new_node = (Borrow*)malloc(sizeof(Borrow)); memcpy(new_node, data, sizeof(Borrow)); new_node->next = NULL; return new_node; } void insert_br_node(Borrow **cur, Borrow *new_node) { (*cur)->next = new_node; *cur = new_node; } void delete_br_node(Borrow **cur, Borrow *del_node) { (*cur)->next = del_node->next; free(del_node); } Book *create_node(Book *data){ Book *new_node = (Book*)malloc(sizeof(Book)); memcpy(new_node, data, sizeof(Book)); new_node->next = NULL; return new_node; } void insert_node(Book **cur, Book *new_node) { (*cur)->next = new_node; *cur = new_node; } void add_node(Book **cur, Book *new_node, Book *next_node) { (*cur)->next = new_node; *cur = new_node; (*cur) -> next = next_node; } void delete_node(Book **cur, Book *del_node) { (*cur)->next = del_node->next; free(del_node); } char *get_string(char * str, int start){ int i = 0; char * temp = (char*)calloc(1024, sizeof(char)); while(str[start] != '|' && str[start] != '\n' && str[start] != '\0'){ temp[i] = str[start]; i++; start++; } return temp; } Book *book_regis(Book **cur) { //책 등록 char input[100]=""; char *name, *purb, *writer, *local, answer; int last_id=0; long isbn; printf("도서명 : "); scanf("%s", input); name = (char *)malloc(strlen(input)); strcpy(name,input); printf("출판사 : "); scanf("%s", input); purb = (char *)malloc(strlen(input)); strcpy(purb,input); printf("저자명 : "); scanf("%s", input); writer = (char *)malloc(strlen(input)); strcpy(writer,input); printf("ISBN : "); scanf("%ld", &isbn); printf("소장처 : "); scanf("%s", input); local = (char *)malloc(strlen(input)); strcpy(local,input); while ((*cur) != NULL) { if((*cur)->book_id > last_id) { last_id = (*cur)->book_id; } *cur = (*cur) -> next; } last_id++; getchar(); printf("\n자동 입력 사항\n\n대여가능 여부 : Y\n도서 번호 : %d\n\n저장하시겠습니까? ",last_id); scanf("%c", &answer); if(answer == 'Y') { Book *book_p = (Book *)malloc(sizeof(Book)); book_p->book_id = last_id; book_p->book_name = (char *)malloc(strlen(name)); strcpy(book_p->book_name, name); book_p->purblisher = (char *)malloc(strlen(purb)); strcpy(book_p->purblisher,purb); book_p->writer = (char *)malloc(strlen(writer)); strcpy(book_p->writer, writer); book_p->isbn = isbn; book_p->local = (char *)malloc(strlen(local)); strcpy(book_p->local, local); book_p->book_rent = 'Y'; fflush(stdout); return book_p; } else { printf("다시 입력하세요\n"); } return NULL; } /*-------------용준-------------*/ void search() {//도서검색실행 FILE *ifp = NULL; ifp = fopen("book.txt", "r"); printf(">> 도서 검색<<\n1.도서명 검색 2. 출판사 검색\n3.ISBN 검색 4. 저자명 검색\n5.전체 검색 6. 이전 메뉴\n\n"); printf("번호를 선택하세요:"); int c;//도서검색에서 선택할 번호입력. scanf("%d", &c); while (getchar() != '\n');//scanf이후 버퍼에서 엔터('\n')지우기 if (c == 1) { findbname(ifp); fclose(ifp); printf("\n\n"); search(); } else if (c == 2) { char s[100];//출판사명 입력할 배열 printf("출판사명을 입력하세요:"); scanf("%[^\n]", s); while (getchar() != '\n'); findpname(ifp, s); fclose(ifp); printf("\n\n"); search(); } else if (c == 3) { findISBN(ifp); fclose(ifp); printf("\n\n"); search(); } else if (c == 4) { char s[100];//작가명 입력할 배열 생성. printf("작가명을 입력하세요:"); scanf("%[^\n]", s); while (getchar() != '\n'); findwriter(ifp, s);//인자로파일포인터와 문자열 전달. fclose(ifp); printf("\n\n"); search(); } else if (c == 5) { findall(ifp); fclose(ifp); printf("\n\n"); search(); } else if (c == 6) { fclose(ifp); return; } else { printf("잘못된 선택입니다. 1~6중에서 선택해주세요.\n"); fclose(ifp); search(); } fclose(ifp); return; } void findbname(FILE *ifp) { char s[100];//도서명입력 LINK head = NULL; LINK p = NULL; LINK q = NULL; LINK r = NULL; int n1 = 0;//대여가능여부 Y의 수 int n2 = 0;//대여가능여부 N의 수 printf("도서명을 입력하세요:"); scanf("%[^\n]", s); while (getchar() != '\n'); while (1) { q = (LINK)malloc(sizeof(book));//book.txt파일 한 줄 읽을 때마다 동적메모리 생성. q->next = NULL; if (head == NULL) { head = q; head->next = NULL; if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", head->bnum, head->bname, head->pname, head->writer, head->ISBN, head->own, &head->YN) != 7) { printf("검색오류입니다.\n"); free(q); break; } if (!strcmp(s, head->bname)) { if (head->YN == 'Y') n1++; else n2++; r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) if (!strcmp(r->ISBN, head->ISBN))//같은 도서 존재하면 YN(대여가능여부)검사 후 대여가능(Y)이면 n1에 1더하고 대여불가능(N)이면 n2에 1더함. { if (r->YN == 'Y') n1++; else n2++; } free(r); if (n1>0) head->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", s); printf("출판사:%s\n", head->pname); printf("저자명:%s\n", head->writer); printf("ISBN :%s\n", head->ISBN); printf("소장처:%s\n", head->own); printf("대여가능 여부:%c(%d/%d)\n", head->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } else { if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) != 7) { free(q); break; } q->next = NULL; p = head; while (p->next != NULL) p = p->next;//p포인터 이동 p->next = q; if (!strcmp(s, q->bname)) { if (q->YN == 'Y') n1++; else n2++; r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) if (!strcmp(r->ISBN, q->ISBN)) { if (r->YN == 'Y') n1++; else n2++; } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } } return; } void findpname(FILE *ifp, char *s) {//출판사검색 FILE *ifp2 = NULL; ifp2 = fopen("book.txt", "r"); LINK head = NULL; LINK p = NULL; LINK q = NULL; LINK r = NULL; int n1 = 0; int n2 = 0; int n3 = 0;//같은책이 몇권인지 셈. while (1) { q = malloc(sizeof(book)); q->next = NULL; if (head == NULL) { head = q; if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) == 7) { if (!strcmp(s, q->pname)) { r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp2, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) { if (!strcmp(r->ISBN, q->ISBN)) { if (r->YN == 'Y') n1++; else n2++; } n3 = n1 + n2 - 1; if (n3 >= 0) if ((!strcmp(r->pname, q->pname)) && (strcmp(r->ISBN, q->ISBN))) { for (int k = 0; n3>k; k++)//같은책수만큼 파일지시자 이동 fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN); fclose(ifp2); findpname(ifp, q->pname); } } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } else { free(q); return; } } else//head!=NULL일떄 { if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) == 7) { q->next = NULL; p = head; while (p->next != NULL) p = p->next; p->next = q; if (!strcmp(s, q->pname)) { r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp2, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) { if (!strcmp(r->ISBN, q->ISBN)) { if (r->YN == 'Y') n1++; else n2++; } n3 = n1 + n2 - 1; if (n3 >= 0) if ((!strcmp(r->pname, q->pname)) && (strcmp(r->ISBN, q->ISBN))) { for (int k = 0; n3>k; k++) fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN); fclose(ifp2); findpname(ifp, q->pname); } } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } else { free(q); return; } } } fclose(ifp2); return; } void findwriter(FILE *ifp, char *s) {//작가명검색 FILE *ifp2 = NULL; ifp2 = fopen("book.txt", "r"); LINK head = NULL; LINK p = NULL; LINK q = NULL; LINK r = NULL; int n1 = 0; int n2 = 0; int n3 = 0;//같은책이 몇권인지셈. while (1) { q = malloc(sizeof(book)); q->next = NULL; if (head == NULL) { head = q; if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) == 7) { if (!strcmp(s, q->writer)) { r = malloc(sizeof(book));//한줄씩 읽으면서 같은 책 찾는 임시 공간 r->next = NULL; while (fscanf(ifp2, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) { if (!strcmp(r->ISBN, q->ISBN))//ISBN이 같은지(도서가 같은지)검사함 { if (r->YN == 'Y') n1++; else n2++; } n3 = n1 + n2 - 1; if (n3 >= 0) if ((!strcmp(r->writer, q->writer)) && (strcmp(r->ISBN, q->ISBN))) { for (int k = 0; n3>k; k++) fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN); fclose(ifp2); findwriter(ifp, q->writer); } } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } else { free(q); return; } } else//head!=NULL { if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) == 7) { q->next = NULL; p = head; while (p->next != NULL) p = p->next;//p포인터 노드 끝으로 이동 p->next = q; if (!strcmp(s, q->writer)) { r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp2, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) { if (!strcmp(r->ISBN, q->ISBN))//ISBN이 같은지(도서가 같은지)검사함 도서 같으면 YN(대여가능여부)검사 후 대여가능(Y)이면 n1에 1더하고 대여불가능(N)이면 n2에 1더함. { if (r->YN == 'Y') n1++; else n2++; } n3 = n1 + n2 - 1; if (n3 >= 0) if ((!strcmp(r->writer, q->writer)) && (strcmp(r->ISBN, q->ISBN))) { for (int k = 0; n3>k; k++) fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN); fclose(ifp2); findwriter(ifp, q->writer); } } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } else { free(q); return; } } } fclose(ifp2); return; } void findISBN(FILE *ifp) { char s[14];//검색할 ISBN LINK head = NULL; LINK p = NULL; LINK q = NULL; LINK r = NULL; int n1 = 0; int n2 = 0; printf("ISBN을 입력하세요:"); scanf("%s", s); while (getchar() != '\n'); while (1) { q = malloc(sizeof(book)); q->next = NULL; if (head == NULL) { head = q; if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) != 7) { printf("검색오류입니다."); free(q); break; } if (!strcmp(s, q->ISBN)) { if (q->YN == 'Y') n1++; else n2++; r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) if (!strcmp(r->ISBN, q->ISBN)) { if (r->YN == 'Y') n1++; else n2++; } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2); printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } else { if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) != 7) { free(q); break; } q->next = NULL; p = head; while (p->next != NULL) { p = p->next; } p->next = q; if (!strcmp(s, q->ISBN)) { if (q->YN == 'Y') n1++; else n2++; r = malloc(sizeof(book)); r->next = NULL; while (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", r->bnum, r->bname, r->pname, r->writer, r->ISBN, r->own, &r->YN) == 7) if (!strcmp(r->ISBN, q->ISBN)) { if (r->YN == 'Y') n1++; else n2++; } free(r); if (n1>0) q->YN = 'Y'; printf("\n\n>> 검색 결과 <<\n"); printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c(%d/%d)\n", q->YN, n2, n1 + n2);//복사 printf("**Y는 대여가능,N은 대여불가를 의미\n**(x/y):(대여된 총 권수/보유하고 있는 총 권수i\n\n"); free(q); break; } } } return; } void findall(FILE *ifp) {//전체검색함수. LINK head = NULL; LINK p = NULL; LINK q = NULL; printf("\n\n>> 검색 결과 <<\n"); while (1) { q = malloc(sizeof(book)); q->next = NULL; if (head == NULL) { head = q; if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) == 7) { printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c\n\n", q->YN); } } else { p = head; while (p->next != NULL) p = p->next; p->next = q; if (fscanf(ifp, "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%[^|]|%c\n", q->bnum, q->bname, q->pname, q->writer, q->ISBN, q->own, &q->YN) == 7) { printf("도서명:%s\n", q->bname); printf("출판사:%s\n", q->pname); printf("저자명:%s\n", q->writer); printf("ISBN :%s\n", q->ISBN); printf("소장처:%s\n", q->own); printf("대여가능 여부:%c\n\n", q->YN); } else { free(q); return; } } } } /*------------용준----------------*/ /*-------------영민-------------*/ void register_member() // 등록 { int student_number; //학번 char password[50]; //비밀번호 char name[20]; //이름 char address[100]; //주소 char phone_number[12]; //전화번호 client* current = (client*)malloc(sizeof(client)); //현재 가리키고 있는 구조체 포인터 client* current_past = (client*)malloc(sizeof(client)); current_past = current = client_head; printf("학번, 비밀번호, 이름, 주소, 전화번호를 입력하세요.\n"); printf("학번: "); scanf("%d", &student_number); getchar(); //기존링크드에 입력받은 값을 학번순으로 삽입하여 새로운 링크드리스트를 만듦 while (current != client_tail) //링크드의 모든 값을 비교하기 전까지 반복 { if (current->std_id < student_number) // 다음 링크드로 넘어감 { current_past = current; current = current->next; } else if (current->std_id > student_number) // 링크드 사이에 새로운 링크드 삽입 { printf("비밀번호: "); scanf("%s", password); getchar(); printf("이름: "); scanf("%[^\n]", name); getchar(); printf("주소: "); scanf("%[^\n]", address); printf("전화번호: "); scanf("%s", phone_number); getchar(); if (current_past == current) //입력받은 학번이 링크드의 가장 첫번째 순서일 경우 { client_head = (client*)malloc(sizeof(client)); client_head->std_id = student_number; strcpy(client_head->password, password); strcpy(client_head->std_name, name); strcpy(client_head->addr, address); strcpy(client_head->ph_num, phone_number); client_head->next = (client*)malloc(sizeof(client)); client_head->next = current; //head의 다음 링크드리스트를 기존의 head로 만듦 client_tail = current->next = (client*)malloc(sizeof(client)); //다음 링크드리스트를 tail로 설정 break; } else { current_past = current_past->next = (client*)malloc(sizeof(client)); current_past->std_id = student_number; //새로운 링크드리스트에 입력 strcpy(current_past->password, password); strcpy(current_past->std_name, name); strcpy(current_past->addr, address); strcpy(current_past->ph_num, phone_number); current_past->next = (client*)malloc(sizeof(client)); current_past->next = current; //새로운 링크드리스트 다음에 이전 링크드리스트 연결하여 삽입 break; } } else { printf("이미 가입되어 있습니다.\n"); break; } } if (current == client_tail) // std_id가 마지막 정렬순서일 경우 { printf("비밀번호: "); scanf("%s", current->password); getchar(); printf("이름: "); scanf("%[^\n]", current->std_name); getchar(); printf("주소: "); scanf("%[^\n]", current->addr); printf("전화번호: "); scanf("%s", current->ph_num); getchar(); current->std_id = student_number; // 마지막 링크에 입력받은 학번 client_tail = current->next = (client*)malloc(sizeof(client)); } FILE* fp = fopen("client.txt", "w"); current = client_head; //링크드리스트의 처음으로 이동 while (current != client_tail) //링크드리스트의 모든 값을 입력하기 전까지 반복 { fprintf(fp, "%d|", current->std_id); fprintf(fp, "%s|", current->password); fprintf(fp, "%s|", current->std_name); fprintf(fp, "%s|", current->addr); fprintf(fp, "%s\n", current->ph_num); current = current->next; //while문 탈출 } fclose(fp); } void member_menu(int id, Borrow *br_cur, Book *bk_cur, Client *cl_cur) //회원메뉴 { system("clear"); int choose; while(1){ printf(">>회원 매뉴<<\n"); printf("1. 도서 검색\t 2. 내 대여 목록\n"); printf("3. 개인정보 수정\t 4. 회원 탈퇴\n"); printf("5. 로그아웃\t 6. 프로그램 종료\n"); printf("번호를 선택하세요:"); scanf("%d",&choose); if(choose==1){ search(); //도서 검색 함수 } if(choose==2){ // 대여 목록 함수 borrow_search(id, br_cur, bk_cur); } if(choose==3){ modify_member(); } if(choose==4){ delete_member(id, br_cur, cl_cur); } if(choose==5){ main(); } if(choose==6){ exit(1); } } } void borrow_search(int id, Borrow *br_cur, Book *bk_cur) { Borrow *br_head = br_cur; Book *bk_head = bk_cur; int year,month,day; struct tm* timeinfo; char *weekday[] = {"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"}; printf(">>내 대여 목록<<\n"); br_cur = br_head -> next; bk_cur = bk_head -> next; while(br_cur != NULL) { if(br_cur->std_id == id) { printf("도서번호 : %d\n", br_cur -> bk_id); while(bk_cur != NULL) { if(bk_cur -> book_id == br_cur->bk_id) { printf("도서명 : %s\n", bk_cur->book_name); } bk_cur=bk_cur->next; } bk_cur=bk_head->next; //날짜 출력 mul_time(br_cur->rent_date, &year, &month, &day); time_t baseTime = make_time(br_cur->rent_date, &year, &month, &day); timeinfo = localtime(&baseTime); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day; mktime(timeinfo); printf("대여 일자 : %ld%s\n",br_cur->rent_date,weekday[timeinfo->tm_wday]); mul_time(br_cur->return_date, &year, &month, &day); baseTime = make_time(br_cur->return_date, &year, &month, &day); timeinfo = localtime(&baseTime); timeinfo->tm_year = year - 1900; timeinfo->tm_mon = month - 1; timeinfo->tm_mday = day; mktime(timeinfo); printf("반납 일자 : %ld%s\n\n",br_cur->return_date,weekday[timeinfo->tm_wday]); } br_cur = br_cur -> next; } br_cur = br_head-> next; } void modify_member() // 수정 { int student_id; student_id = atoi(id_login); char change_password[300]; // 현재 비밀번호 client * current = (client*)malloc(sizeof(client)); current = client_head; while (current != client_tail) // 현재 학번과 일치하는 링크탐색 { if (current->std_id == student_id) break; else current = current->next; } while (1) { printf("개인정보를 수정하기 위해 현재 비밀번호를 입력하세요.\n비밀먼호 : "); scanf("%s", change_password); if (!strcmp(current->password, change_password)) { printf("수정할 비밀번호, 주소, 전화번호를 입력하세요.\n"); printf("비밀번호 : "); scanf("%s", current->password); getchar(); printf("주소 : "); gets(current->addr); printf("전화번호 : "); scanf("%s", current->ph_num); getchar(); FILE * fp = fopen("client.txt", "w"); current = client_head; while (current != client_tail) { fprintf(fp, "%d|", current->std_id); fprintf(fp, "%s|", current->password); fprintf(fp, "%s|", current->std_name); fprintf(fp, "%s|", current->addr); fprintf(fp, "%s\n", current->ph_num); current = current->next; } fclose(fp); break; } else { printf("비밀번호가 틀립니다.\n"); change_password[0] = '\0'; } } } void client_add() // txt 에 저장된 값을 링크드리스트에 저장해주는 함수 { FILE* fp = fopen("client.txt", "r"); client* current= (client*)malloc(sizeof(client)); current= client_head; while (!feof(fp)) //파일에 더이상 읽을 값이 없으면 반복문 종료. { fscanf(fp, "%d|", &current->std_id); fscanf(fp, "%[^|]|", current->password); fscanf(fp, "%[^|]|", current->std_name); fscanf(fp, "%[^|]|", current->addr); fscanf(fp, "%[^\n]\n", current->ph_num); current = current->next = (client*)malloc(sizeof(client)); //다음 링크드ㄹ스트로로 이동 } fclose(fp); client_tail = current; } void delete_member(int id, Borrow *br_cur, Client *cl_cur) // 탈퇴 { Borrow *br_head = br_cur; Client *cl_head = cl_cur, *del_node, *tail_node; int br_check=0; br_cur = br_head -> next; while(br_cur != NULL) { if(br_cur -> std_id == id) { br_check ++; } br_cur = br_cur -> next; } br_cur = br_head -> next; FILE *cfp = fopen("./client.txt", "w"); if(br_check == 0) { //대여중인 도서가 없을때 if(cl_head -> next-> std_id == id) { //첫번째 노드일때 delete_cl_node(&cl_head, cl_head->next); while(cl_cur != NULL) { if(cl_cur->std_id != 0) { fprintf(cfp, "%d|%s|%s|%s|%s\n", cl_cur->std_id, cl_cur->password, cl_cur->std_name, cl_cur->addr, cl_cur->ph_num); } cl_cur=cl_cur->next; } } else { //중간이나 끝일때 cl_cur=cl_head->next; while(cl_cur != NULL) { //끝에서 두번째 노드 찾기 if(cl_cur->next->next == NULL) { tail_node = cl_cur; break; } cl_cur=cl_cur->next; } if(tail_node->next->std_id == id) { //마지막 노드일때 delete_cl_node(&tail_node, tail_node->next); cl_cur=cl_head->next; while(cl_cur != NULL) { fprintf(cfp, "%d|%s|%s|%s|%s\n", cl_cur->std_id, cl_cur->password, cl_cur->std_name, cl_cur->addr, cl_cur->ph_num); cl_cur = cl_cur -> next; } } else { //중간일때 cl_cur=cl_head->next; while(cl_cur != NULL) { if(cl_cur->next->std_id == id) { //전에 노드 위치저장 del_node = cl_cur; break; } cl_cur=cl_cur->next; } cl_cur=cl_head->next; delete_cl_node(&del_node, del_node->next); while(cl_cur != NULL) { fprintf(cfp, "%d|%s|%s|%s|%s\n", cl_cur->std_id, cl_cur->password, cl_cur->std_name, cl_cur->addr, cl_cur->ph_num); cl_cur = cl_cur -> next; } } } printf("탈퇴 성공\n"); } else { printf("탈퇴 불가능\n"); } fclose(cfp); } /*-------------영민-------------*/
C
#include <linux/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <poll.h> #include <sys/select.h> #include <sys/time.h> /* 定义按键值 */ #define KEY_VALUE 0X0F /* 按键按下键值 */ #define KEY_INVAL 0X00 /* 无效的按键值 */ /* *argc 应用程序参数个数 *argv 具体的参数内容,字符串形式 *命令调用: ./led <filename> <1:2> 1读2写 *./led /dev/led 1 *./led /dev/led 2 */ int main(int argc, char *argv[]) { int fd = 0; int ret = 0, cnt = 0; char *filename = argv[1]; int keyvalue; fd_set select_readfds; struct timeval timeout; struct pollfd poll_readfds[1];//要监视的文件描述符和要监视的事件,是一个数组;一个描述符为一个元素 if (argc != 2){ printf("error usage!! Plese use : ./keyAPP <filename> "); return -1; } /*open*/ fd = open(filename, O_RDWR | O_NONBLOCK); if (fd < 0){ printf("open %s failed!!\r\n", filename); return -1; } while(1) { #if 0 FD_ZERO(&select_readfds);//清零可读集合 FD_SET(fd, &select_readfds);//将fd添加到可读集合 timeout.tv_sec = 0; timeout.tv_usec = 500000;//500ms ret = select(fd+1, &select_readfds, NULL, NULL, &timeout); switch (ret) { case 0://超时 printf("read timeout ! \r\n"); break; case -1://错误 printf("read error ! \r\n"); break; default://可读 if (FD_ISSET(fd, &select_readfds)){ ret = read(fd, &keyvalue, sizeof(keyvalue)); if (ret >= 0) { printf("KEY0 Press, value = %#x \r\n", keyvalue); } } break; } #else poll_readfds[0].fd = fd; poll_readfds[0].events = POLLIN;//监视可读事件 ret = poll(&poll_readfds[0], 1, 500);//1为监视的文件描述符数量 switch (ret) { case 0: printf("read timeout ! \r\n"); break; case -1: printf("read error ! \r\n"); break; default: ret = read(fd, &keyvalue, sizeof(keyvalue)); if (ret >= 0) { printf("KEY0 Press, value = %#x \r\n", keyvalue); } break; } #endif } /*close*/ ret = close(fd); if (ret < 0){ printf("close %s failed!!", filename); return -1; } return 0; }
C
#include <stdio.h> #include<time.h> int binarys(int a); int main() { int x,n; clock_t start,end; printf("Enter a number to find the square root"); scanf("%d",&x); start=clock(); { n=binarys(x); printf("Square root of %d is %d \n",x,n); } end=clock(); double t=(double)(end-start)/(double)(CLOCKS_PER_SEC); printf("Runtime is %lf",t); return 0; } int binarys(int a) { int mid,low=0,high,result,y; high=a-1; while(low<=high) { mid=(low+high)/2 ; y=mid*mid ; if(y==a) return mid ; else if(y<a) {low=mid+1; result=mid; } else high=mid-1; } return result; }
C
#ifndef QUEUE_H_ #define QUEUE_H_ #include <stdint.h> struct queue_t { uint8_t *buffer; unsigned int size; uint8_t head_idx; uint8_t tail_idx; }; void queue_init(struct queue_t* q); void queue_push_back(struct queue_t* q, uint8_t c); uint8_t queue_pop_front(struct queue_t* q); int queue_empty(struct queue_t* q); unsigned int queue_size(struct queue_t* q); #endif /* QUEUE_H_ */
C
/* Сегмент памяти Данные (Data) Также в сегменте памяти данные хранятся статические переменные. Статические переменные создаются внутри функций с помощью ключевого слова static. Такие переменные создаются и инициализируются только один раз, во время первого вызова функции. Во время последующих вызовов функция не создаёт эту переменную заново, а работает с уже созданной переменной. В целом, эти переменные похожи на глобальные переменные, только доступиться к ним можно только из одной функции. В этом примере, строка static int n = 0; исполнится только 1 раз, при первом вызове функции counter. */ #include <stdio.h> void counter() { static int n = 0; n++; printf("%i\n", n); } int main() { counter(); counter(); counter(); } /* Задачи: 1) Что напечатает данная программа? 2) Создайте функцию adder, которая будет принимать на вход число и возвращать сумму всех чисел, которые приходили на вход этой функции за время выполнения программы. printf("%i\n", adder(10)); // Напечатает 10 printf("%i\n", adder(15)); // Напечатает 25 printf("%i\n", adder(70)); // Напечатает 95 */
C
/** *Author: wuyangchun *Date: 2012-06-05 *Description: 哈希表, 大小不够的时候会自动扩展,但数据被移除的时候不会自动缩小,需要手动调用, 这样可以避免添加和删除的时候刚好在自动扩展的边界上,导致不停的调整哈希表大小 * **/ #ifndef CLIB_HASH_H_ #define CLIB_HASH_H_ #include <clib/types.h> #ifdef __cplusplus extern "C" { #endif typedef struct _hash_table hash_table_t; typedef struct _hash_table_iter hash_table_iter; /* *@brief 创建哈希表 *@param in size 默认大小,如果超过这个大小,每次增加这么多个,如果为0,采取默认策略 *@param in hash_func 根据key得到哈希值的函数 *@param in key_compare_func 判断key是否相等的函数 *@param user_data 用户自定义数据,会传入给key_compare_func *@param in key_destroy_func 当从哈希表中移除一条数据时,负责释放由key指向的内存 *@param in value_destroy_func 当从哈希表中移除一条数据时,负责释放由value指向的内存 *@return 新哈希表 */ hash_table_t* hash_table_new(/*uint size,*/ hash_func hash_func, compare_func key_compare_func, void *user_data, destroy_func key_destroy_func, destroy_func value_destroy_func); /* *@brief 释放哈希表 *@param in hash_table 待释放哈希表 *@return */ void hash_table_free(hash_table_t *hash_table); /* *@brief 向哈希表插入数据,如果key已经存在,替换掉value值 如果创建hash_table的时候指定了value_destroy_func,则调用该函数释放原来的value *@param in hash_table 哈希表 *@param in key 待插入的key *@param in value 待插入的数据 *@return */ void hash_table_insert(hash_table_t *hash_table, void *key, void *value); /* *@brief 替换key对应的value,如果key不存在,插入新的数据 *@param in hash_table 哈希表 *@param in key 待替换value的key *@param in value 新的value *@return */ //void hash_table_replace(hash_table_t *hash_table, void *key, void *value); /* *@brief 删除key及关联的value *@param in hash_table 哈希表 *@param in key 删除的key *@return 如果key不存在,返回false,否则返回true */ bool hash_table_remove(hash_table_t *hash_table, const void *key); /* *@brief 删除哈希表内所有数据,同时调用hash_table_resize *@param in hash_table 哈希表 *@return */ void hash_table_remove_all(hash_table_t *hash_table); /* *@brief 获取key对应的数据,并从哈希表中移除相应的数据 * 但不调用key和value的destroy_func *@param in hash_table 哈希表 *@param in lookup_key 待查找的key *@param out orikey 存放找到的key,如果不需要保存返回值,传入NULL即可 *@param out value 存放找到的value,如果不需要保存返回值,传入NULL即可 *@return 如果key存在,返回true,否则返回false */ bool hash_table_steal(hash_table_t *hash_table, const void *lookup_key, void **orikey, void **value); /* *@brief 根据key查找对应的value *@param in hash_table 哈希表 *@param in key 待查找的key *@return 如果key存在,返回value,否则返回NULL * *@notice 如果value本身的值就是NULL,该函数无法区分key是否存在 * 这种情况下需要调用hash_table_lookup_extended函数 */ void *hash_table_lookup(hash_table_t *hash_table, const void *key); /* *@brief 判断key是否存在 *@param in hash_table 哈希表 *@param in key 待查找的key *@return 如果key存在,返回true,否则返回false */ bool hash_table_contains(hash_table_t *hash_table, const void *key); /* *@brief 根据key查找对应的value *@param in hash_table 哈希表 *@param in lookup_key 待查找的key *@param out orikey 存放找到的key,如果不需要,传入NULL即可 *@param out value 存放找到的value,如果不需要,传入NULL即可 *@return 如果key存在,返回true,否则返回false */ bool hash_table_lookup_extended(hash_table_t *hash_table, const void *lookup_key, void **orikey, void **value); /* *@brief 遍历哈希表,如果遍历函数返回true,则停止遍历 *@param in hash_table 哈希表 *@param in func 遍历函数 *@param in user_data 用户自定义数据,调用遍历函数的时候会传过去 *@return 如果全部遍历完成,返回true,否则返回false */ bool hash_table_foreach(hash_table_t *hash_table, traverse_pair_func func, void *user_data); /* *@brief 遍历哈希表,如果遍历函数返回true,则删除掉对应的key和value *@param in hash_table 哈希表 *@param in func 遍历函数 *@param in user_data 用户自定义数据,调用遍历函数的时候会传过去 *@return 实际删除的数据个数 */ uint hash_table_foreach_remove(hash_table_t *hash_table, traverse_pair_func func, void *user_data); /* *@brief 获取哈希表大小(存放的数据个数) *@param in hash_table 哈希表 *@return 哈希表大小 */ uint hash_table_size(hash_table_t *hash_table); /* *@brief 根据哈希表的实际大小,重新调整哈希表的占用空间,释放多余的空间 *@param in hash_table 哈希表 *@return */ void hash_table_resize(hash_table_t *hash_table); /* *@brief 获取哈希表的key列表 *@param in hash_table 哈希表 *@return key列表,包含所有的key */ //list_t* hash_table_get_keys(hash_table_t *hash_table); /* *@brief 获取哈希表的value列表 *@param in hash_table 哈希表 *@return value列表,包含所有的value */ //list_t* hash_table_get_values(hash_table_t *hash_table); /* *@brief 初始化哈希表的迭代器 * 初始化后调用hash_table_iter_next就可以获得哈希表的第一个数据 *@param in iter 迭代器 *@param in hash_table 哈希表 *@return */ //void hash_table_iter_init(hash_table_iter *iter, hash_table_t *hash_table); /* *@brief 取哈希表中的下一个数据 *@param in iter 迭代器 *@param out key 取到的key *@param out value 取到的value *@return */ //bool hash_table_iter_next(hash_table_iter *iter, void **key, void **value); /* *@brief 根据迭代器得到关联的哈希表 *@param in iter 迭代器 *@return 关联的哈希表,如果还没有关联哈希表,则返回NULL */ //hash_table_t* hash_table_iter_get_hash_table(hash_table_iter *iter); /* *@brief 移除迭代器指向的数据 *@param in iter 迭代器 *@return */ //void hash_table_iter_remove(hash_table_iter *iter); /* *@brief 用新的value替换掉迭代器指向的value *@param in iter 迭代器 *@param in value 新的value *@return */ //void hash_table_iter_replace(hash_table_iter *iter, void *value); /* 哈希函数 */ uint str_hash(const void *v); uint int32_hash(const void *v); uint int_hash(const void *v); uint int64_hash(const void *v); uint double_hash(const void *v); uint direct_hash(const void *v); uint ip_hash(const void *v); //用来释放哈希表的destroy_func函数 extern void hash_table_destroy_func(void* data); #ifdef __cplusplus } #endif #endif /* CLIB_HASH_H_ */
C
//pc2.c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <time.h> #define P 2 #define C 4 #define N 20 #define iteraciones 30 sem_t mutex; sem_t empty; sem_t full; int buffer[N]; int indiceProd=-1; int indiceCons=-1; int main(){ pthread_t hProd[P], hCons[C]; int vProd[P], vCons[C]; int status; int *resProd, *resCons; int totalProd=0, totalCons=0; void *productor(void *p); void *consumidor(void *p); sem_init(&mutex, 0, 1); sem_init(&full, 0, 0); sem_init(&empty, 0, N); //CREACION DE P HILOS PRODUCTORES for(int i=0; i<P; i++){ vProd[i]=i; if((status=pthread_create(&hProd[i], NULL, &productor, (void*)&vProd[i]))){ printf("Error al crear al hilo productor %d\n", i); exit(status); } } //CREACION DE C HILOS CONSUMIDORES for(int i=0; i<C; i++){ vCons[i]=i; if((status=pthread_create(&hCons[i], NULL, &consumidor, (void*)&vCons[i]))){ printf("Error al crear al hilo consumidor %d\n", i); exit(status); } } //ESPERAMOS A QUE FINALICEN LOS P HILOS PRODUCTORES for(int i=0; i<P; i++){ pthread_join(hProd[i], (void**)&resProd); totalProd+=*resProd; } //ESPERAMOS A QUE FINALICEN LOS C HILOS CONSUMIDORES for(int i=0; i<C; i++){ pthread_join(hCons[i], (void**)&resCons); totalCons+=*resCons; } //RESULTADO FINAL printf("TOTAL PRODUCIDO = %d\n", totalProd); printf("TOTAL CONSUMIDO = %d\n", totalCons); sem_destroy(&mutex); sem_destroy(&full); sem_destroy(&empty); } void *productor(void *p){ int valor, aux=0; srand(time(NULL)); for(int i=0; i<iteraciones; i++){ sem_wait(&empty); valor=rand()%1000; aux+=valor; sem_wait(&mutex); indiceProd=(indiceProd+1)%N; buffer[indiceProd]=valor; printf("Se ha introducido el valor %d en el buffer %d\n", valor, indiceProd); sem_post(&mutex); sem_post(&full); } int *retorno=(int*)malloc(sizeof(int)); *retorno=aux; pthread_exit((void*)retorno); } void *consumidor(void *p){ int valor, aux=0; int iteracionesCons=(iteraciones*P/C); for(int i=0; i<iteracionesCons; i++){ sem_wait(&full); sem_wait(&mutex); indiceCons=(indiceCons+1)%N; valor=buffer[indiceCons]; aux+=valor; printf("Se ha consumido %d del indice %d\n", valor, indiceCons); sem_post(&mutex); sem_post(&empty); } int *retorno=(int*)malloc(sizeof(int)); *retorno=aux; pthread_exit((void*)retorno); }
C
#include<stdio.h> //#include<conio.h> void main() { float area,h,w; //clrscr(); printf("Enter Height of Rectangle: "); scanf("%f",&h); printf("Enter Width of Rectangle: "); scanf("%f",&w); area=h*w; printf("Area of Rectangle is: %0.2f",area); //getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 192 //strcpyn(buffer, 192, argv[1], strlen(argv[1])) void strcpyn(char * destination, unsigned int destination_length, char * source, unsigned int source_length) { unsigned int i; for (i = 0; i <= destination_length && i <= source_length; i++) destination[i] = source[i]; //i <= strlen(argv[1]) && i<=192 , we will overwrite by one byte, which is the frame pointer? //buff[i] } void copy_user_argument(char * user_argument, unsigned int argument_length) { char buffer[BUFFER_SIZE]; //buffer size == 192 strcpyn(buffer, sizeof(buffer), user_argument, argument_length); } void launch(char * user_argument) { copy_user_argument(user_argument, strlen(user_argument)); //copy_user_argument(argv[1], strlen(argv[1])) } int main(int argc, char * argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s ARGUMENT\n", argv[0]); exit(EXIT_FAILURE); } launch(argv[1]); return(0); }
C
/* * File: service.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include "service.h" #include "util.h" void handle_client(int socket) { int reqsize =0; int bufsize=100; char buf[bufsize]; typedef struct reqStruct { http_method method; int headerSize; int contentLength; char* host; char* pragma; char* acceptedEncoding; char* body; } reqStruct; /* TODO Loop receiving requests and sending appropriate responses, * until one of the conditions to close the connection is * met. overall framework: while (connection is open) receive request: while (request header is not complete) receive more data from socket into temp buffer if buffer is not big enough for old data + new data, realloc it to fit more data copy temp buffer to the end of buffer if request method is not GET read content length let read = received data minus size of the header if buffer is not big enough for header size plus content length, realloc it to fit more data while read < content length receive more data into temp buffer copy temp buffer to end of buffer parse command build response send response */ while(connection is open) { reqStruct* r = (reqStruct*) malloc(sizeof (reqStruct)); r->body=NULL; char tempbuf[100]; //receive request //initial recv for first data, keep track of size of request reqsize=recv(socket, buf, 99, 0); //make sure receive whole request while(http_header_complete(buf,bufsize)==-1) { int nextChunk=recv(socket, tempbuf, 99, 0); if (bufsize<reqsize+nextChunk) { buf=realloc(buf, bufsize*2); bufsize*=2; } for (int i =0; i<nextChunk; i++) { buf[reqsize+i] = tempbuf[i]; } reqsize+=nextChunk; } r->headerSize=http_header_complete(buf,reqsize); r->method=http_parse_method(buf); //make sure to get the body if not a GET request //if it isn't need to make sure body is fully received int read =0; if (method!=METHOD_GET) { r->contentLength=atoi(http_parse_header_field(buf,bufsize,"Content-Length")); bufsize++; read = reqsize-r->headerSize; //loop until receive all of the contents of body while(read < r->contentLength) { int nextChunk= recv(socket, tempbuf, 99, 0); (if (bufsize<reqsize+nextChunk)) { buf=realloc(buf, bufsize*2); bufsize*=2; } for(int i =0; i<nextChunk; i++) { buf[reqsize+i]=tempbuf[i]; } reqsize+=nextChunk; } r->body=http_parse_body(buf,reqsize); } //parse r->host=http_parse_header_field(buf,reqsize,"Host"); r->pragma=http_parse_header_field(buf,reqsize,"Pragma"); r->acceptedEncoding=http_parse_header_field(buf,reqsize,"Accepted-Encoding"); //build repsonse //send r epsonse } return; }
C
// // SeqList.c // SeqList // // Created by Lrc mac on 2018/6/19. // Copyright © 2018年 Lrc mac. All rights reserved. // #include <stdio.h> #include "SeqList.h" void SeqListInit(SeqList* pSeq) { for (int i = 0; i<MAX_SIZE; i++) { pSeq->_array[i] = 0; pSeq->_size = 0; } } void SeqListPushBack(SeqList* pSeq, DataType data) { pSeq->_array[pSeq->_size] = data; pSeq->_size ++; } void SeqListPopBack(SeqList* pSeq) { pSeq->_size --; } void SeqListPushFront(SeqList* pSeq, DataType data) { if (pSeq->_size == MAX_SIZE) { printf("size==MAX_SIZE can't Push!\n"); return; } for (int i = pSeq->_size; i>0; i--) { pSeq->_array[i] = pSeq->_array[i-1]; } pSeq->_array[0] = data; pSeq->_size++; } void SeqListPopFront(SeqList* pSeq) { for (int i = 0; i<pSeq->_size-1; i++) { pSeq->_array[i] = pSeq->_array[i+1]; } pSeq->_size--; } void SeqListInsert(SeqList* pSeq, int pos, DataType data) { if (pSeq->_size == MAX_SIZE) { printf("size==MAX_SIZE can't Push!\n"); return; } for (int i = pSeq->_size; i>pos; i--) { pSeq->_array[i] = pSeq->_array[i-1]; } pSeq->_array[pos] = data; pSeq->_size++; } void SeqListErase(SeqList* pSeq, int pos) { if (pos>=0 && pos < pSeq->_size) { for (int i = pos; i<pSeq->_size-1; i++) { pSeq->_array[i] = pSeq->_array[i+1]; } pSeq->_size--; } } int SeqListFind(SeqList* pSeq, DataType data) { for (int i = 0; i<pSeq->_size; i++) { if (data == pSeq->_array[i]) { return i; } } return -1; } void SeqListRemove(SeqList* pSeq, DataType data) { // for (int i = 0; i<pSeq->_size; i++) // { // if (data == pSeq->_array[i]) // { // SeqListErase(pSeq, i); // } // } int pos = SeqListFind(pSeq, data); if (pos >=0) { SeqListErase(pSeq, pos); } } void SeqListRemoveAll(SeqList* pSeq, DataType data) { for (int i = 0; i<pSeq->_size; i++) { if (pSeq->_array[i] == data) { SeqListErase(pSeq, i); i--; } } } //----------------- void PrintList(SeqList* pSeq) { for (int i = 0; i<pSeq->_size; i++) { printf("%d ",pSeq->_array[i]); } printf("\n"); } void swap(DataType* p1,DataType* p2) { DataType tmp = *p1; *p1 = *p2; *p2 = tmp; } void BubbleSort(SeqList* pSeq) { for (int i = 0; i<pSeq->_size; i++) { for (int j = 0; j<pSeq->_size-1-i; j++) { if (pSeq->_array[j]<pSeq->_array[j+1]) { swap(pSeq->_array+j, pSeq->_array+j+1); } } } } void SelectSort(SeqList* pSeq) { for (int i = 0; i<pSeq->_size-1; i++) { for (int j = i+1; j<pSeq->_size; j++) { if (pSeq->_array[i]<pSeq->_array[j]) { swap(pSeq->_array+i, pSeq->_array+j); } } } } void BinarySearch(SeqList* pSeq, DataType data) { int start = 0; int end = pSeq->_size-1; while (start<=end) { int mid = (start+end)/2; if (data == pSeq->_array[mid]) { printf("the pos = %d\n",mid); return; } else if (data < pSeq->_array[mid]) { end = mid-1; } else { start = mid+1; } } printf("Can't find!\n"); }
C
//---------------------------------------------------------------------------- // support functions and macros for C style strings use //---------------------------------------------------------------------------- #include <string.h> inline void CopyString( char *pszDest, int nDestSize, const char *pszOrig) { if (pszOrig) strncpy(pszDest, pszOrig, nDestSize); pszDest[nDestSize-1] = '\0'; } inline void CatString( char *pszDest, int nDestSize, const char *pszOrig) { int nLen = strlen(pszDest); if (nLen < nDestSize - 1) { CopyString(pszDest + nLen, nDestSize - nLen, pszOrig); } } //....to compare strings without the !=0 stupid shit inline bool IsEqualString( const char* psz1, const char* psz2 ) { return (strcmp( psz1, psz2 )==0); } inline bool IsEqualStringNoCase( const char* psz1, const char* psz2 ) { if (psz1==NULL || psz2==NULL) return psz1==psz2; else return (_stricmp( psz1, psz2 )==0); } inline bool IsEqualStringNoCaseNumChars( const char* psz1, const char* psz2, int _iNumChars ) { if (psz1==NULL || psz2==NULL) return psz1==psz2; else return (_strnicmp( psz1, psz2, _iNumChars )==0); } //...sprintf with buffer size checks void SprintfSafe( char* _pszBuf, int _iBufTam, const char* _pszFmt, ... ); //...gets memory for an string, and copies it. WARNING, that memory has to be freed by the user #define ALLOC_COPY_STRING( _pszOrig ) AllocCopyString( _pszOrig, __FILE__, __LINE__ ) inline char* AllocCopyString( const char* _pszOrig, const char* _pszFileNEW, uint _uLineNEW ) { char* pszDest = NULL; if (_pszOrig) { pszDest = NEW_MOVED( _pszFileNEW, _uLineNEW ) char[ strlen(_pszOrig)+1]; strcpy( pszDest, _pszOrig ); } return pszDest; } // Macros to manage strings that are not pointers. Because the simple check, strings with a size of 4 cant be used either. #define CAT_2_STRINGS( buf, str1, str2 ) \ { \ ASSERT(sizeof(buf)!=4); \ CopyString( buf, sizeof(buf), str1 ); \ CatString ( buf, sizeof(buf), str2 ); \ } #define COPY_STRING( dest, ori ) \ { \ ASSERT(sizeof(dest)!=4); \ CopyString( dest, sizeof(dest), ori ); \ } //...appends an string into another but dest CANT be a pointer. (it will fail when it is an string of size 4 also...) #define CAT_STRING( dest, ori ) \ { \ ASSERT( sizeof(dest)!=4 ); \ CatString( dest, sizeof(dest), ori ); \ } ////////////////////////////////////////////////////////////////////////// inline const char* GetLitONOFF( bool _bPar ) { if (_bPar) return "ON"; else return "OFF"; } ////////////////////////////////////////////////////////////////////////// inline const char* GetLitBool( bool _bPar ) { if (_bPar) return "TRUE"; else return "FALSE"; } ////////////////////////////////////////////////////////////////////////// // retunrs true if the string is with "true" //---------------------------------------------------------------------- inline bool Str2Bool( const char* _psz ) { char szBuf[128]; const char* psz = _psz; while (*psz==' ') { psz++; } int iDest = 0; while (*psz!=0 && *psz!=' ' && iDest<sizeof(szBuf)-1) { szBuf[iDest]=*psz; psz++; iDest++; } szBuf[iDest] = 0; return IsEqualStringNoCase( szBuf, "true" ); } ////////////////////////////////////////////////////////////////////////// // builds a file name with adding date and time to a given root filename void AddTimeDateToFileName( char* _pszNewFileName, int _iSize, const char* _pszOldFileName ); ////////////////////////////////////////////////////////////////////////// // MACRO_PRINTF // // Macro to read printf data style in a function // the format string has to be _pszFmt #define MACRO_PRINTF( szBuffer, BufferSize ) \ const int BUFFER_SIZE = BufferSize; \ char szBuffer[BUFFER_SIZE]; \ { \ const int CHECK = 0x0114455AA; \ va_list ap; \ va_start(ap, _pszFmt); \ *((int*)(szBuffer+BUFFER_SIZE-4)) = CHECK; \ vsprintf(szBuffer, _pszFmt, ap); \ ASSERTM( *((int*)(szBuffer+BUFFER_SIZE-4)) == CHECK, ("Buffer overrun, probably memory leak now\n") ); \ va_end(ap); \ } //---------------------------------------------------------------------- // MACRO_PRINTF_FULLSIZE #define MACRO_PRINTF_FULLSIZE( szBuffer, BufferSize ) \ const int BUFFER_SIZE = BufferSize; \ char szBuffer[BUFFER_SIZE]; \ { \ char szBufferTemp[BUFFER_SIZE+4]; \ const int CHECK = 0x0114455AA; \ va_list ap; \ va_start(ap, _pszFmt); \ *((int*)(szBufferTemp+BUFFER_SIZE)) = CHECK; \ vsprintf(szBufferTemp, _pszFmt, ap); \ ASSERTM( *((int*)(szBufferTemp+BUFFER_SIZE)) == CHECK, ("Buffer overrun, probably memory leak now\n") ); \ va_end(ap); \ CopyString( szBuffer, sizeof(szBuffer), szBufferTemp ); \ } \ // this function returns the numeric value in an string of the style "nx", where n is a number. ie: "3x", "100x" int GetMultiplicatorValue( const char* _psz );
C
#ifndef __KLIBC_H #define __KLIBC_H /* 在屏幕上输出字符,字符串及整数 */ #include "global_type.h" //打印一个字符 void kputchar( char ch ) ; //打印字符串,以'\0'为结尾字符 void kputstr( const char *str ) ; //以2进制打印一个uint32_t类型 void kput_uint32_bin( uint32_t num ) ; //以16进制形式打印一个uint32_t类型 void kput_uint32_hex( uint32_t num ) ; //以10进制打印一个uint32_t类型 void kput_uint32_dec( uint32_t num ) ; #endif
C
#include <stdio.h> /*Esse programa calcula x^n*/ int main(void) { int n , x , resultado , contador ; printf("Entre com os valores de x e n: "); scanf("%d %d", &x , &n); resultado = 1; contador = 1; while(contador <=n) { resultado = resultado * x; contador = contador + 1; } printf("O resultado de %d elevado a %d é %d.\n", x , n , resultado); return 0; }
C
/** * @Author: Kyle Andrews * @Date: September 23, 2010 * @Description: Takes the factorial via while looping */ #include <stdio.h> main() { int start,stop=1,factorial=1; printf("Take the factorial of: "); scanf("%i",&start); if (start >25) { printf("Error. Answer too large!"); return; } while(stop<=start) { factorial=factorial*stop; stop++; } printf("Factorial of %i is: %d",start,factorial); //getchar(); //using getchar as a method of "pause" to keep terminal open. return 0; }
C
int searchInsert(int* nums, int numsSize, int target) { int i; for(i = 0; i < numsSize; i++) if(nums[i] >= target) return i; return i; }
C
// #include<stdio.h> void Display(char *str) { int i=0,iCnt=0; if(str == NULL) { return; } while(*str!=0) { iCnt++; str++; } str--; while(iCnt>0) { printf("%c",*str); iCnt--; str--; } } int main() { char Arr[10]; int iRet=0; printf("Enter string:"); scanf("%[^\n]s",Arr); Display(Arr); printf("\n%s\n",Arr); return 0; }
C
#include "cub.h" int mapp(t_map *m, int fd) { char *line; int linelen = 0; int count = 0; while (get_next_line(fd, &line)) { int i = 0; while(line[i] == ' ' || line[i] == '\t') ++i; if(line[i] == 'R') { ++i; m->width = ft_atoi(line + i); if (m->width > 1920) m->width = 1920; i+= ft_numlen(m->width); m->height = ft_atoi(line + i); if (m->height > 1080) m->height = 1080; } else if(line[i] == 'N' && line[i + 1] == 'O') { i += 2; while(line[i] == ' ' || line[i] == '\t') ++i; m->northfd = ft_strcpy(m->northfd, line + i); } else if(line[i] == 'S' && line[i + 1] == 'O') { i += 2; while(line[i] == ' ' || line[i] == '\t') ++i; m->southfd = ft_strcpy(m->southfd, line + i); } else if(line[i] == 'W' && line[i + 1] == 'E') { i += 2; while(line[i] == ' ' || line[i] == '\t') ++i; m->westfd = ft_strcpy(m->westfd, line + i); } else if(line[i] == 'E' && line[i + 1] == 'A') { i += 2; while(line[i] == ' ' || line[i] == '\t') ++i; m->eastfd = ft_strcpy(m->eastfd, line + i); } else if(line[i] == 'S') { ++i; while(line[i] == ' ' || line[i] == '\t') ++i; m->spritefd = ft_strcpy(m->spritefd, line + i); } else if(line[i] == 'F') { ++i; while(line[i] == ' ' || line[i] == '\t') ++i; int x = 0; int y = 0; int z = 0; x = ft_atoi(line + i); i += ft_numlen(x) + 1; y = ft_atoi(line + i); i += ft_numlen(y) + 1; z = ft_atoi(line + i); m->floor = create_rgb(x,y,z); } else if(line[i] == 'C') { ++i; while(line[i] == ' ' || line[i] == '\t') ++i; int x = 0; int y = 0; int z = 0; x = ft_atoi(line + i); i += ft_numlen(x) + 1; y = ft_atoi(line + i); i += ft_numlen(y) + 1; z = ft_atoi(line + i); m->ceiling = create_rgb(x,y,z); } else { if(line[0] == '\0') continue; if (linelen < (int)ft_strlen(line)) linelen = ft_strlen(line); count++; } } if(line[0] != '\0') count++; close(fd); fd = open(m->fname, O_RDONLY); m->maph = count; m->mapw = linelen; m->map = malloc(sizeof(char*)*count); for (int i = 0; i < count; i++) m->map[i] = malloc(linelen); count = 0; int j = 0; int c = 0; int s = 0; while (get_next_line(fd, &line)) { int i = 0; while(line[i] == ' ' || line[i] == '\t') ++i; if(line[i] == 'R') continue; else if(line[i] == 'N' && line[i + 1] == 'O') continue; else if(line[i] == 'S' && line[i + 1] == 'O') continue; else if(line[i] == 'W' && line[i + 1] == 'E') continue; else if(line[i] == 'E' && line[i + 1] == 'A') continue; else if(line[i] == 'S') continue; else if(line[i] == 'F') continue; else if(line[i] == 'C') continue; else { j = 0; c = 0; if(line[0] == '\0') continue; while(line[j] == ' ' || line[j] == '\t') { m->map[count][c++] = '0'; j++; } while(line[j]) { if(line[j] != '\t' && line[j] != ' ') { m->map[count][c++] = line[j]; if (line[j++] == '2') s++; } else j++; } while(c < linelen) m->map[count][c++] = '0'; count++; } } if(line[0] != '\0') { c = 0; j = 0; while(line[j] == ' ' || line[j] == '\t') { m->map[count][c++] = '0'; j++; } while(line[j]) { if(line[j] != '\t' && line[j] != ' ') { m->map[count][c++] = line[j]; if (line[j++] == '2') s++; } else j++; } while(c < linelen) m->map[count][c++] = '0'; count++; } close(fd); return (s); } void init(t_map *m) { int i; i = 0; int j; int c = 0; while(i < m->maph) { j = 0; while(j < m->mapw) { if(m->map[i][j] == 'S') { m->p.pos_x = i + 0.5; m->p.pos_y = j + 0.5; m->p.xdir = 1; m->p.ydir = 0; m->p.xplane = 0; m->p.yplane = 0.66; break; } else if(m->map[i][j] == 'N') { m->p.pos_x = i + 0.5; m->p.pos_y = j + 0.5; m->p.xdir = -1; m->p.ydir = 0; m->p.xplane = 0; m->p.yplane = -0.66; break; } else if(m->map[i][j] == 'E') { m->p.pos_x = i + 0.5; m->p.pos_y = j + 0.5; m->p.xdir = 0; m->p.ydir = 1; m->p.xplane = -0.66; m->p.yplane = 0; break; } else if(m->map[i][j] == 'W') { m->p.pos_x = i + 0.5; m->p.pos_y = j + 0.5; m->p.xdir = 0; m->p.ydir = -1; m->p.xplane = 0.66; m->p.yplane = 0; break; } else if (m->map[i][j] == '2') { m->s[c].x = i + 0.5; m->s[c].y = j + 0.5; c++; } j++; } i++; } } int error_check(t_map *m) { int fd = open(m->fname, O_RDONLY); char *line; while (get_next_line(fd, &line)) { int i = 0; if (line[i] == 'R' || (line[i] == 'N' && line[i + 1] == 'O') || (line[i] == 'S' && line[i + 1] == 'O') || (line[i] == 'W' && line[i + 1] == 'E') || (line[i] == 'E' && line[i + 1] == 'A') || line[i] == 'S' || line[i] == 'F' || line[i] == 'C') continue; else { while(line[i]) { if (line[i] == '0' || line[i] == '1' || line[i] == '2' || line[i] == 'W' || line[i] == 'E' || line[i] == 'S' || line[i] == 'N' || line[i] == ' ' || line[i] == '\t') ++i; else return (-1); } } } close(fd); return (1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sort_algoritms.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: asybil <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/15 19:51:55 by asybil #+# #+# */ /* Updated: 2020/11/25 01:01:12 by asybil ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/push_swap.h" /* ** Map of compares: ** raw_map[0] - compare top_to_middle ** raw_map[1] - compare middle_to_bottom ** raw_map[2] - compare bottom_to_top ** Where value of 1 is '>', -1 is '<'. */ static void get_compared_map(int *raw_map, t_stack *a) { raw_map[0] = a->head->value > a->head->next->value ? 1 : -1; raw_map[1] = a->head->next->value > a->foots->value ? 1 : -1; raw_map[2] = a->foots->value > a->head->value ? 1 : -1; } /* ** Return value: -1 if can`t sorted. 0 - sorted. */ int sort_three_values(t_stack *a) { int compared_map[3]; if (a->stack_size != 3) return (-1); if (!is_sorted_stack(a)) return (0); get_compared_map(compared_map, a); if (compared_map[2] == -1) { if (compared_map[0] > compared_map[1]) reverse_rotate(a); else if (compared_map[0] < compared_map[1]) rotate(a); else swap(a); } else swap(a); return (sort_three_values(a)); } /* ** TODO */ int sort_five_values(t_stack *a, t_stack *b) { while (a->stack_size != 3) push_to(a, a, b); sort_three_values(a); if (b->stack_size == 2) { if (b->head->value < b->head->next->value) { return (1); } } return (1); } void sort_many_values(t_sorter *s) { s->ranges = range_pack_from_stack(s->a); move_all_stack_b(s); validate_stack(s->b); push_all_to_a(s->a, s->b); }
C
/* CLIPS Version 4.30 4/25/89 */ /*******************************************************/ /* "C" Language Integrated Production System */ /* EVALUATION MODULE */ /*******************************************************/ #include <stdio.h> #include "clips.h" /***************************************/ /* GLOBAL EXTERNAL FUNCTION DEFINITIONS */ /***************************************/ extern struct draw *add_symbol(); extern char *symbol_string(); /***************************************/ /* LOCAL INTERNAL VARIABLE DEFINITIONS */ /***************************************/ static struct funtab *fctn_list = NULL; /****************************************/ /* GLOBAL INTERNAL VARIABLE DEFINITIONS */ /****************************************/ struct test *new_fctn_args; /*###############################################*/ /*###############################################*/ /*###### ######*/ /*###### FUNCTION DEFINITION AND EXECUTION ######*/ /*###### ######*/ /*###############################################*/ /*###############################################*/ /********************************************************************/ /* generic_compute: */ /********************************************************************/ int generic_compute(problem,compute_result) struct test *problem; struct values *compute_result; { float result; struct draw *dresult; char (*cp)(); struct draw *(*dp)(); float (*fp)(); char cbuff[2], rc; struct test *old_arg; if (problem == NULL) { clips_system_error(1201); cl_exit(5); } switch (problem->type) { case STRING: case WORD: compute_result->type = problem->type; compute_result->val.hvalue = problem->val.hvalue; break; case NUMBER: compute_result->type = NUMBER; compute_result->val.fvalue = problem->val.fvalue; break; case FCALL: old_arg = new_fctn_args; new_fctn_args = problem; switch(problem->val.fun_ptr->fun_type) { case 'v' : (*problem->val.fun_ptr->ip)(); compute_result->type = RVOID; compute_result->val.fvalue = 0.0; break; case 'i' : result = (float) (*problem->val.fun_ptr->ip)(); compute_result->type = NUMBER; compute_result->val.fvalue = result; break; case 'f' : fp = (float (*)()) problem->val.fun_ptr->ip; result = (*fp)(); compute_result->type = NUMBER; compute_result->val.fvalue = result; break; case 's' : dp = (struct draw *(*)()) problem->val.fun_ptr->ip; dresult = (*dp)(); compute_result->type = STRING; compute_result->val.hvalue = dresult; break; case 'w' : dp = (struct draw *(*)()) problem->val.fun_ptr->ip; dresult = (*dp)(); compute_result->type = WORD; compute_result->val.hvalue = dresult; break; case 'c' : cp = (char (*)()) problem->val.fun_ptr->ip; rc = (*cp)(); cbuff[0] = rc; cbuff[1] = EOS; compute_result->type = WORD; compute_result->val.hvalue = add_symbol(cbuff); break; case 'm' : (*problem->val.fun_ptr->ip)(compute_result); break; case 'u' : (*problem->val.fun_ptr->ip)(compute_result); break; default : clips_system_error(1202); cl_exit(5); break; } new_fctn_args = old_arg; break; case BWORDS: case BWORD: cl_print("werror","\n*** ERROR ***\n"); cl_print("werror","Variables cannot be accessed at this level\n"); break; default: clips_system_error(1203); cl_exit(5); break; } return; } /*************************************************************/ /* define_function: Used to define a system or user external */ /* function so that CLIPS can access it. */ /*************************************************************/ define_function(name,return_type,pointer,defn_name) char *name, *defn_name; char return_type; int (*pointer)(); { struct funtab *new_function; if ( (return_type != 'i') && (return_type != 'f') && (return_type != 's') && (return_type != 'w') && (return_type != 'c') && (return_type != 'v') && (return_type != 'm') && (return_type != 'u') ) { cl_print("werror","ERROR: Illegal function type passed to define_function\n"); cl_print("werror","Legal values are i, f, s, w, c, v, m, and u.\n"); return(0); } new_function = get_struct(funtab); new_function->fun_name = name; new_function->fun_type = return_type; new_function->ip = pointer; new_function->next = fctn_list; new_function->defn_name = defn_name; fctn_list = new_function; return(1); } /************************************************************/ /* find_function: Returns true (1) if a function name is in */ /* the function list, otherwise returns false (0). */ /************************************************************/ struct funtab *find_function(fun_name) char *fun_name; { struct funtab *fun_list; fun_list = fctn_list; if (fun_list == NULL) { return(NULL); } while (strcmp(fun_name,fun_list->fun_name) != 0) { fun_list = fun_list->next; if (fun_list == NULL) { return(NULL); } } return(fun_list); } /***********************************************************/ /* RSTRING: Purpose is to return a pointer to a character */ /* array that represents an argument to a function call, */ /* called by the fctn. */ /***********************************************************/ char *rstring(string_pos) int string_pos; { int count = 1; struct values result; struct test *arg_ptr; /*=====================================================*/ /* Find the appropriate argument in the argument list. */ /*=====================================================*/ arg_ptr = new_fctn_args->arg_list; while ((arg_ptr != NULL) && (count < string_pos)) { count++; arg_ptr = arg_ptr->next_arg; } if (arg_ptr == NULL) { non_exist_error("rstring",new_fctn_args->val.fun_ptr->fun_name,string_pos); set_execution_error(TRUE); return(NULL); } /*=================================================*/ /* Return the value associated with that argument. */ /*=================================================*/ generic_compute(arg_ptr,&result); if ((result.type != WORD) && (result.type != STRING)) { wrong_type_error("rstring",new_fctn_args->val.fun_ptr->fun_name, string_pos,"string"); set_execution_error(TRUE); return(NULL); } return(result.val.hvalue->contents); } /***********************************************************/ /* RHASH: Purpose is to return a pointer to a character */ /* array that represents an argument to a function call, */ /* called by the fctn. */ /***********************************************************/ struct draw *rhash(string_pos) int string_pos; { int count = 1; struct values result; struct test *arg_ptr; /*=====================================================*/ /* Find the appropriate argument in the argument list. */ /*=====================================================*/ arg_ptr = new_fctn_args->arg_list; while ((arg_ptr != NULL) && (count < string_pos)) { count++; arg_ptr = arg_ptr->next_arg; } if (arg_ptr == NULL) { non_exist_error("rhash",new_fctn_args->val.fun_ptr->fun_name,string_pos); set_execution_error(TRUE); return(NULL); } /*=================================================*/ /* Return the value associated with that argument. */ /*=================================================*/ generic_compute(arg_ptr,&result); if ((result.type != WORD) && (result.type != STRING)) { wrong_type_error("rhash",new_fctn_args->val.fun_ptr->fun_name, string_pos,"string"); set_execution_error(TRUE); return(NULL); } return(result.val.hvalue); } /**************************************************************/ /* rfloat: Returns the nth argument of a function call. The */ /* argument should be a floating point number, otherwise an */ /* error will occur. */ /**************************************************************/ float rfloat(float_pos) int float_pos; { int count = 1; struct values result; struct test *arg_ptr; /*=====================================================*/ /* Find the appropriate argument in the argument list. */ /*=====================================================*/ arg_ptr = new_fctn_args->arg_list; while ((arg_ptr != NULL) && (count < float_pos)) { count++; arg_ptr = arg_ptr->next_arg; } if (arg_ptr == NULL) { non_exist_error("rfloat",new_fctn_args->val.fun_ptr->fun_name,float_pos); set_execution_error(TRUE); return(1.0); } /*=================================================*/ /* Return the value associated with that argument. */ /*=================================================*/ generic_compute(arg_ptr,&result); if (result.type != NUMBER) { wrong_type_error("rfloat",new_fctn_args->val.fun_ptr->fun_name, float_pos,"number"); set_execution_error(TRUE); return(1.0); } return(result.val.fvalue); } /********************************************************/ /* runknown: returns an argument thats type is unknown. */ /********************************************************/ struct values *runknown(arg_pos,val_ptr) int arg_pos; struct values *val_ptr; { int count = 1; struct test *arg_ptr; /*=====================================================*/ /* Find the appropriate argument in the argument list. */ /*=====================================================*/ arg_ptr = new_fctn_args->arg_list; while ((arg_ptr != NULL) && (count < arg_pos)) { count++; arg_ptr = arg_ptr->next_arg; } if (arg_ptr == NULL) { non_exist_error("runknown",new_fctn_args->val.fun_ptr->fun_name,arg_pos); set_execution_error(TRUE); return(NULL); } /*=================================================*/ /* Return the value associated with that argument. */ /*=================================================*/ generic_compute(arg_ptr,val_ptr); return(val_ptr); } /********************************************************/ /* rmultype: Returns the type of the nth element of an */ /* argument of type MULTIPLE. */ /********************************************************/ int rmultype(result,nth) struct values *result; int nth; { int length; struct element *elm_ptr; if (result->type != MULTIPLE) return(NULL); length = (result->end - result->begin) + 1; if ((nth > length) || (nth < 1)) return(NULL); elm_ptr = result->origin->atoms; return(elm_ptr[result->begin + nth - 1].type); } /********************************************************/ /* rmulstring: */ /********************************************************/ char *rmulstring(result,nth) struct values *result; int nth; { int length; struct element *elm_ptr; if (result->type != MULTIPLE) return(NULL); length = (result->end - result->begin) + 1; if ((nth > length) || (nth < 1)) return(NULL); elm_ptr = result->origin->atoms; return(symbol_string(elm_ptr[result->begin + nth - 1].val.hvalue)); } /********************************************************/ /* rmulhash: */ /********************************************************/ struct draw *rmulhash(result,nth) struct values *result; int nth; { int length; struct element *elm_ptr; if (result->type != MULTIPLE) return(NULL); length = (result->end - result->begin) + 1; if ((nth > length) || (nth < 1)) return(NULL); elm_ptr = result->origin->atoms; return(elm_ptr[result->begin + nth - 1].val.hvalue); } /********************************************************/ /* rmulfloat: */ /********************************************************/ float rmulfloat(result,nth) struct values *result; int nth; { int length; struct element *elm_ptr; if (result->type != MULTIPLE) return(0.0); length = (result->end - result->begin) + 1; if ((nth > length) || (nth < 1)) return(0.0); elm_ptr = result->origin->atoms; return(elm_ptr[result->begin + nth - 1].val.fvalue); } /********************************************************/ /* make_unknown: */ /********************************************************/ struct values *make_unknown(unk_type,string,number) struct draw *string; int unk_type; float number; { static struct values unk_val; unk_val.type = unk_type; if (unk_type == NUMBER) { unk_val.val.fvalue = number; } else { unk_val.val.hvalue = string; } return(&unk_val); } /********************************************************/ /* assign_unknown: */ /********************************************************/ assign_unknown(unk_type,string,number,unk_val) struct draw *string; int unk_type; float number; struct values *unk_val; { unk_val->type = unk_type; if (unk_type == NUMBER) { unk_val->val.fvalue = number; } else { unk_val->val.hvalue = string; } } /******************************************************************/ /* num_args: Returns the length of the argument list for a */ /* function call. Useful for system and user defined functions */ /* which accept a variable number of arguments. */ /******************************************************************/ num_args() { int count = 0; struct test *arg_ptr; arg_ptr = new_fctn_args->arg_list; while (arg_ptr != NULL) { count++; arg_ptr = arg_ptr->next_arg; } return(count); } /*********************************************/ /* ADD_ELEMENT: */ /*********************************************/ add_element(new_fact,position,data_type,svalue,ivalue) struct fact *new_fact; int position; int data_type; char *svalue; float ivalue; { struct element *elem_ptr; if ((position > new_fact->fact_length) || (position < 1)) { return(-1); } position--; elem_ptr = new_fact->atoms; elem_ptr[position].type = data_type; if (data_type == NUMBER) { elem_ptr[position].val.fvalue = ivalue; } else { elem_ptr[position].val.hvalue = add_symbol(svalue); } return(0); } /*********************************************/ /* NON_EXIST_ERROR: */ /*********************************************/ static int non_exist_error(acc_fun_name,fun_name,arg_num) char *acc_fun_name, *fun_name; int arg_num; { cl_print("werror","Function "); cl_print("werror",acc_fun_name); cl_print("werror"," received a request from function "); cl_print("werror",fun_name); cl_print("werror"," for argument #"); print_long_int("werror",(long int) arg_num); cl_print("werror"," which is non-existent\n"); } /*********************************************/ /* WRONG_TYPE_ERROR: */ /*********************************************/ static int wrong_type_error(acc_fun_name,fun_name,arg_num,type) char *acc_fun_name, *fun_name, *type; int arg_num; { cl_print("werror","Function "); cl_print("werror",acc_fun_name); cl_print("werror"," received a request from function "); cl_print("werror",fun_name); cl_print("werror"," for argument #"); print_long_int("werror",(long int) arg_num); cl_print("werror"," which is not of type "); cl_print("werror",type); cl_print("werror","\n"); } /*****************/ /* GET_FCTN_LIST */ /*****************/ struct funtab *get_fctn_list() { return(fctn_list); } /*****************/ /* SET_FCTN_LIST */ /*****************/ set_fctn_list(value) struct funtab *value; { fctn_list = value; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahammou- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/23 16:50:46 by ahammou- #+# #+# */ /* Updated: 2019/06/03 10:50:40 by ahammou- ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/fdf.h" /* ** Bresenham algorithm ** */ void draw_line(t_mlx *m, t_dot tabxy, int x, int y) { t_dot tabxy_s; t_dot tabxy_e; double e[2]; m->x0 = tabxy.x; m->y0 = tabxy.y; tabxy_s.x = abs(x - m->x0); tabxy_e.x = m->x0 < x ? 1 : -1; tabxy_s.y = abs(y - m->y0); tabxy_e.y = m->y0 < y ? 1 : -1; e[0] = (tabxy_s.x > tabxy_s.y ? tabxy_s.x : -tabxy_s.y) * 0.5; while (m->x0 != x || m->y0 != y) { mlx_pixel_put(m->mlx, m->win, m->x0, m->y0, m->clr); e[1] = e[0]; e[1] > -tabxy_s.x ? e[0] -= tabxy_s.y : 1 == 1; e[1] > -tabxy_s.x ? m->x0 += tabxy_e.x : 1 == 1; e[1] < tabxy_s.y ? e[0] += tabxy_s.x : 1 == 1; e[1] < tabxy_s.y ? m->y0 += tabxy_e.y : 1 == 1; } } /* ** formula for isometric projection ** */ t_dot rasterize_iso(t_mlx *m, int x, int y, int z) { t_dot tabxy; tabxy.x = m->dx + ((0.7 * (double)x) - (0.7 * (double)y)); tabxy.y = m->dy + z * m->z + ((0.7 * 0.5) * (double)x + (0.7 * 0.5) * (double)y); return (tabxy); } void draw_m_iso(t_mlx *m, int x, int y) { t_dot tabxy; tabxy = rasterize_iso(m, x, y, m->coord[y / m->sy][x / m->sx]); if (x / m->sx < m->nb_col - 1 && y / m->sy < m->nb_l) { draw_line(m, tabxy, m->dx + 0.7 * (double)(x + m->sx) - 0.7 * (double)y, m->dy + m->coord[y / m->sy][x / m->sx + 1] * m->z + (0.7 * 0.5) * (x + m->sx) + (0.7 * 0.5) * y); } if (y / m->sy < m->nb_l - 1 && x / m->sx <= m->nb_col) draw_line(m, tabxy, m->dx + 0.7 * (double)x - 0.7 * (double)(y + m->sy), m->dy + m->coord[y / m->sy + 1][x / m->sx] * m->z + (0.7 * 0.5) * x + (0.7 * 0.5) * (y + m->sy)); } /* ** formula for parallele porjection ** */ t_dot rasterize_para(t_mlx *m, int x, int y, int z) { t_dot tabxy; tabxy.x = m->dx + x + 0.7 * (z * m->z); tabxy.y = m->dy + y + (0.7 * 0.5) * (z * m->z); return (tabxy); } void draw_m_para(t_mlx *m, int x, int y) { t_dot tabxy; tabxy = rasterize_para(m, x, y, m->coord[y / m->sy][x / m->sx]); if (x / m->sx < m->nb_col - 1 && y / m->sy < m->nb_l) draw_line(m, tabxy, m->dx + (x + m->sx) + 0.7 * (m->coord[y / m->sy][x / m->sx + 1] * m->z), m->dy + y + (0.7 * 0.5) * (m->coord[y / m->sy][x / m->sx + 1] * m->z)); if (y / m->sy < m->nb_l - 1 && x / m->sx <= m->nb_col) draw_line(m, tabxy, m->dx + x + 0.7 * (m->coord[y / m->sy + 1][x / m->sx] * m->z), m->dy + (y + m->sy) + (0.7 * 0.5) * (m->coord[y / m->sy + 1][x / m->sx] * m->z)); }
C
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* This code explain about how to enable the clock before talking to any * peripheral and if clock is not enable then is not possible to talk to that * peripheral. * * 1) To enable the ADC1 which is connected on the APB2 bus we have to access the APB2ENR register * and enable the bit which enable the clock for ADC1 same is done in line-->50 * 2) To enable the GPIOA which is connected on the AHB1 bus we have to access the AHB1ENR register * and enable the bit which enable the clock for GPIOa same is done in line-->51 */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f446xx.h" int main(void) { ADC_TypeDef *pADC; RCC_TypeDef *pRRC; GPIO_TypeDef *pGPIO; pGPIO = GPIOA;//link to the base address of GPIO port A pRRC = RCC;//link to base address of the RCC pADC = ADC1;//link the base address of the ADC1 to the pADC pointer //First enable the clock the access the peripheral register pRRC->APB2ENR = pRRC->APB2ENR | (1 << 8); pRRC->AHB1ENR = pRRC->AHB1ENR | 1;//GPIOA //After clock is enable then access the register pADC->CR1 = 0x08; pGPIO->PUPDR = 0x22; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "../../include/Queue.h" #include "mu_test.h" int CheckQueueContent(Queue* _queue, int* _arr, int _size) { size_t i; int num = 3,*val = &num; for (i = 0; i < _size; ++i) { ASSERT_THAT( Queue_Remove(_queue,(void**) &val) == QUEUE_SUCCESS); ASSERT_THAT( *val == _arr[i] ); } return PASS; } UNIT(create_normal) Queue *_queue = Queue_Create(); ASSERT_THAT(_queue != NULL); Queue_Destroy(_queue,NULL); END_UNIT UNIT(Queue_insert) Queue *_queue; int i,num; int expected[] = { 0, 1, 2, 3, 4 }; _queue = Queue_Create(); ASSERT_THAT(_queue != NULL); for (i = 0; i < 5; ++i) { num = i; ASSERT_THAT( Queue_Insert(_queue, &num) == QUEUE_SUCCESS); } CheckQueueContent(_queue, expected,5); Queue_Destroy(_queue,NULL); END_UNIT UNIT(Queue_underflow) Queue *_queue; int num = 3,i,*val = &num; int expected[] = { 0, 1, 2, 3, 4 }; _queue = Queue_Create(); ASSERT_THAT(_queue != NULL); for (i = 0; i < 5; ++i) { ASSERT_THAT( Queue_Insert(_queue, &i) == QUEUE_SUCCESS); } CheckQueueContent(_queue, expected,5); ASSERT_THAT(Queue_Remove(_queue,(void**) &val) == QUEUE_UNDERFLOW); Queue_Destroy(_queue,NULL); END_UNIT /* */ TEST_SUITE(Queue test) TEST(create_normal) TEST(Queue_insert) TEST(Queue_underflow) /* TEST(Queue_overflow) */ END_SUITE
C
#include<stdio.h> #include<math.h> int main(void){ int length,width,height; scanf("%d %d %d",&length,&width,&height); int a,b,c; a=length*width; b=width*height; c=length*height; printf("the surface area is %d\n",2*(a+b+c)); printf("the volumn is %d\n",sqrt(a*b*c)); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct bovino { int* num_id; float* peso; } Bovino; int main () { int i, n, menor = 0, maior = 0; float menor_peso = 1000000, maior_peso = 0; Bovino boi; scanf("%d", &n); boi.num_id = (int*) malloc(sizeof(int)*n); boi.peso = (float*) malloc(sizeof(float)*n); for(i = 0 ; i < n ; ++i) { scanf("%d %f", &boi.num_id[i], &boi.peso[i]); if(boi.peso[i] > maior_peso) { maior_peso = boi.peso[i]; maior = i; } if(boi.peso[i] < menor_peso) { menor_peso = boi.peso[i]; menor = i; } } printf("Gordo: id: %d peso: %.2fKg\nMagro: id: %d peso: %.2fKg\n", boi.num_id[maior], maior_peso, boi.num_id[menor], menor_peso); return 0; }
C
include<stdio.h> int main() { int n; printf("enter the year\n"); scanf("%d",&n); if(n%400==0) printf("leap year\n"); else if(n%4==0&&n%100!=0) printf("year is leap year\n"); else printf("not a leap year\n"); return 0; }
C
// // Created by HP on 2019/9/26. // #include <stdio.h> #include <stdlib.h> int main() { printf("How long the r\y\g lights cotinue?"); int red,green,yellow; scanf("%d %d %d",&red,&yellow,&green); if(red > 106 || green > 106 || yellow > 106) { printf("input again."); scanf("%d %d %d",&red,&yellow,&green); } int n; printf("sum of :"); scanf("%d",&n); int sum = 0; for(int i = 0;i < n;i++) { int k,t; scanf("%d %d",&k,&t); switch(k) { case 0: sum += t; break; case 1: sum += t; break; case 2: sum += t + red; } } printf("%d",sum); return 0; }
C
/* * the possible way to implement strcpy() function. */ #include <stdio.h> #include <string.h> char *strcpy(char *strDest, const char *strSrc) { char *temp = strDest; while (*strDest++ = *strSrc++); return temp; } void* my_memcpy(void *dst, void *src, unsigned int count) { void *ret = dst; // If dst and src do not overlap, copy from low address to high address. if (dst <= src || (char *) dst >= (char *) src + count) { while (count--) { *(char *) dst = *(char *) src; dst = (char *) dst + 1; src = (char *) src + 1; } } else { // dst and src overlap, copy from high address to low address. dst = (char *) dst + count - 1; src = (char *) src + count - 1; while (count--) { *(char *) dst = *(char *) src; dst = (char *) dst - 1; src = (char *) src - 1; } } return ret; } int main(int argc, char *argv[]) { { char dest[10] = { 0 }; char src[10] = "hello"; printf("dest str: %s|\n", strcpy(dest, src)); } { /* // memory overlap */ /* char str[10] = "abc\0"; */ /* strcpy(str + 1, str); */ /* */ /* printf("str: %s|\n", str); */ } { // with overlap version char str[10] = "abc\0"; my_memcpy(str + 1, str, strlen(str) + 1); printf("str: %s|\n", str); } return 0; }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "tools.h" #include "io.h" double f (int i,int j){ return fabs(i-j); //return (i>j)?i:j; } double identity (int i, int j){ if (i==j) return 1.; else return 0.; } void searchMainBlock(void *inv, void *inoutv, int *len, MPI_Datatype *MPI_mainBlockInfo){ mainBlockInfo *in = (mainBlockInfo *) inv; mainBlockInfo *inout = (mainBlockInfo *) inoutv; int i; if (!MPI_mainBlockInfo){ } for (i=0; i<*len; ++i){ if(in->label){ if(inout->label){ if(in->minnorm<inout->minnorm){ inout->minnorm = in->minnorm; inout->rank = in->rank; inout->min_k = in->min_k; } } else{ inout->minnorm = in->minnorm; inout->rank = in->rank; inout->min_k = in->min_k; } } inout->label += in->label; } } int readMatrixByRows(char* name, double *a, int matrix_side, int block_side, int total_pr, int current_pr){ FILE *fp = 0; int ret=0, loc=0; int i, j, count=0; double trash; int block_number = 0; int block_number_proc_id = 0; int block_number_per_process = 0; int total_block_rows = (matrix_side + block_side - 1)/block_side; int current_pr_block_rows = (total_block_rows + total_pr - 1)/total_pr; int block_string_size = matrix_side * block_side; int matrix_size_current_pr = current_pr_block_rows *block_string_size; fp = fopen(name, "r"); if (!fp){ loc = 1; } MPI_Allreduce(&loc, &ret, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if (ret){ return -1; } loc=0; for(i=0; i<matrix_side; i++){ block_number = i/block_side; block_number_proc_id = block_number % total_pr; block_number_per_process = block_number / total_pr; if(block_number_proc_id==current_pr){ for(j=0; j<matrix_side; j++){ loc+=fscanf(fp, "%lf", a + block_number_per_process*block_string_size + (i%block_side)*matrix_side + j); count++; } } else{ for(j=0; j<matrix_side; j++){ loc+=fscanf(fp, "%lf", &trash); } } } if(loc<matrix_side*matrix_side){ loc=1; } else{ loc=0; } MPI_Allreduce(&loc, &ret, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if (ret){ if(current_pr==0){ printf("Failed to read whole matrix\n"); } return -1; } fclose(fp); for(j=count;j<matrix_size_current_pr;j++){ a[j]=0.; } return 0; } int readMatrixByColumns(char* name, double *a, int matrix_side, int block_side, int total_pr, int current_pr){ FILE *fp = 0; int ret=0, loc=0; int i, j; int count = 0; double trash; int block_number = 0; int block_number_proc_id = 0; int block_number_per_process = 0; int total_block_rows, total_full_block_rows, block_size, block_string_size; int max_block_rows_pp, max_rows_pp, short_block_string_size, last_block_row_proc_id, last_block_row_in_current_pr; int small_block_row_width, small_block_size, current_pr_full_rows, last_block_row_width, matrix_size_current_pr; initParameters(matrix_side, block_side, total_pr, current_pr, &total_block_rows, &total_full_block_rows, &block_size, &block_string_size, &max_block_rows_pp, &max_rows_pp, &short_block_string_size, &last_block_row_proc_id, &last_block_row_in_current_pr, &small_block_row_width, &small_block_size, &current_pr_full_rows, &last_block_row_width, &matrix_size_current_pr); fp = fopen(name, "r"); if (!fp){ loc = 1; } MPI_Allreduce(&loc, &ret, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if (ret){ if(current_pr==0){ printf("Failed to open file\n"); } return -1; } loc=0; for(i=0; i<matrix_side; i++){ for(j=0;j<matrix_side;j++){ block_number = j/block_side; block_number_proc_id = block_number % total_pr; block_number_per_process = block_number / total_pr; if(block_number_proc_id==current_pr){ loc+=fscanf(fp, "%lf", a + i*max_rows_pp + block_number_per_process*block_side + j%block_side); count++; } else{ loc+=fscanf(fp, "%lf", &trash); } } for(;count<(i+1)*max_rows_pp;count++){ a[count]=0.; } } if(loc<matrix_side*matrix_side){ loc=1; } else{ loc=0; } MPI_Allreduce(&loc, &ret, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if (ret){ if(current_pr==0){ printf("Failed to read whole matrix\n"); } return -1; } fclose(fp); return 0; } int initMatrixByRows(double *a, int n, int m, int p, int k){ int i,j; int pos_i=0; int total_block_rows = (n+m-1)/m; int max_block_rows = ((total_block_rows + p-1)/p); int max_rows = max_block_rows*m; for (i=0; i<max_rows; i++){ for (j=0; j<n; j++){ pos_i = (i/m); pos_i = pos_i*p*m + i%m; pos_i += k*m; if (pos_i<n){ a[i*n+j]=f(pos_i,j); } else a[i*n+j]=0.; } } return 0; } int initMatrixByColumns(double *a, int n, int m, int p, int k){ int i,j; int pos_j=0; int total_block_rows = (n+m-1)/m; int max_block_rows = ((total_block_rows + p-1)/p); int max_rows = max_block_rows*m; for (i=0; i<n; i++){ for (j=0; j<max_rows; j++){ pos_j = (j/m); pos_j = pos_j*p*m + j%m; pos_j += k*m; if (pos_j<n){ a[i*max_rows+j]=f(i,pos_j); } else a[i*max_rows+j]=0.; } } return 0; } /* double MPI_getResidual(double *reinitialized, double *reversed, int matrix_side, int block_side, int total_pr, int current_pr, int *blocks_order, int *blocks_order_reversed, double *buf_string, double *buf_string_2, double *buf_1, double *buf_2){ double residual = -1.; double local_residual = -1.; double *temp_vect = 0; double *temp_block = 0; double *temp_block_for_multiplication = 0; double *buf = 0; int i, j, k, l, m, pos_j, pos_k; int current_pr_rows; int total_block_rows, total_full_block_rows, block_size, block_string_size; int max_block_rows_pp, max_rows_pp, short_block_string_size, last_block_row_proc_id, last_block_row_in_current_pr; int small_block_row_width, small_block_size, current_pr_full_rows, last_block_row_width, matrix_size_current_pr; initParameters(matrix_side, block_side, total_pr, current_pr, &total_block_rows, &total_full_block_rows, &block_size, &block_string_size, &max_block_rows_pp, &max_rows_pp, &short_block_string_size, &last_block_row_proc_id, &last_block_row_in_current_pr, &small_block_row_width, &small_block_size, &current_pr_full_rows, &last_block_row_width, &matrix_size_current_pr); current_pr_rows = current_pr_full_rows * block_side; if ((small_block_row_width)&&(current_pr==last_block_row_proc_id)){ current_pr_rows += small_block_row_width; } temp_vect = buf_string; buf = buf_string_2; //careful here temp_block = buf_1; temp_block_for_multiplication = buf_2; for(i=0;i<max_rows_pp;i++){ temp_vect[i]=0.; } for(i=0;i<total_pr;i++){ if(current_pr==i){ for(j=0;j<matrix_size_current_pr;j++){ buf[j]=reinitialized[j]; } } MPI_Bcast(buf, matrix_size_current_pr, MPI_DOUBLE, i, MPI_COMM_WORLD); for(j=0; j<max_block_rows_pp; j++){ pos_j = blocks_order_reversed[j*total_pr + current_pr]; for(k=0; k<max_block_rows_pp;k++){ for(l=0;l<block_size;l++){ temp_block[l]=0.; } for(l=0;l<total_full_block_rows;l++){ simpleMatrixMultiply(reversed + j*block_string_size + l*block_size, buf + l*short_block_string_size + k*block_size, temp_block_for_multiplication, block_side, block_side, block_side); addToMatrix(temp_block, temp_block_for_multiplication, block_size); } if(small_block_row_width){ simpleMatrixMultiply(reversed + j*block_string_size + total_full_block_rows*block_size, buf + total_full_block_rows*short_block_string_size + k*small_block_size, temp_block_for_multiplication, block_side, small_block_row_width, block_side); addToMatrix(temp_block, temp_block_for_multiplication, block_size); } //try not to forget to subtract Id matrix! pos_k = k*total_pr + i; if(pos_j==pos_k){ if(pos_j<total_full_block_rows){ for(l=0;l<block_side;l++){ for(m=0;m<block_side;m++){ if(l==m){ temp_block[l*block_side+m]-=1; } } } } else{ for(l=0;l<small_block_row_width;l++){ for(m=0;m<small_block_row_width;m++){ if(l==m){ temp_block[l*block_side+m]-=1.; } } } } } if((current_pr!=last_block_row_proc_id)||(pos_j<total_full_block_rows)){ for(l=0; l<block_side; l++){ for(m=0; m<block_side; m++){//5X combo!!! temp_vect[j*block_side+l]+=fabs(temp_block[l*block_side+m]); } } } else{ for(l=0; l<small_block_row_width; l++){ for(m=0; m<block_side; m++){ temp_vect[j*block_side+l]+=fabs(temp_block[l*block_side+m]); } } } } } } local_residual = -1.; for(i=0; i<current_pr_rows;i++){ if(local_residual<temp_vect[i]){ local_residual = temp_vect[i]; } } #ifdef RESIDAL_PRINT for(i=0;i<current_pr_rows;i++){ pos_j = current_pr*block_side + (i/block_side)*total_pr*block_side + i%block_side; printf("%d row %.3le residual\n", pos_j, temp_vect[i]); } #endif MPI_Allreduce(&local_residual, &residual, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); return residual; } */ int initParameters(int matrix_side, int block_side, int total_pr, int current_pr, int *total_block_rows, int *total_full_block_rows, int *block_size, int *block_string_size, int *max_block_rows_pp, int *max_rows_pp, int *short_block_string_size, int *last_block_row_proc_id, int *last_block_row_in_current_pr, int *small_block_row_width, int *small_block_size, int *current_pr_full_rows, int *last_block_row_width, int *matrix_size_current_pr){ *total_block_rows = (matrix_side+block_side-1)/block_side; *total_full_block_rows = matrix_side/block_side; *block_size = block_side*block_side; *block_string_size = matrix_side*block_side; *max_block_rows_pp = (*total_block_rows + total_pr - 1)/total_pr; *max_rows_pp = (*max_block_rows_pp) * block_side; *short_block_string_size = (*max_block_rows_pp) * (*block_size); *last_block_row_proc_id = (*total_block_rows-1)%total_pr; *last_block_row_in_current_pr = (current_pr<=(*last_block_row_proc_id)) ? (*max_block_rows_pp) : (*max_block_rows_pp-1); *small_block_row_width = matrix_side - (*total_full_block_rows)*block_side; *small_block_size = block_side*(*small_block_row_width); *current_pr_full_rows = (((*last_block_row_proc_id)!=current_pr)||((*small_block_row_width)==0)) ? (*last_block_row_in_current_pr) : (*last_block_row_in_current_pr-1);//¿¿¿¿¿ ¿¿¿¿¿¿¿ ¿¿¿¿¿¿¿ ¿¿ ¿¿¿¿¿¿¿ ¿¿¿¿¿¿¿ *last_block_row_width = ((*current_pr_full_rows)!=(*last_block_row_in_current_pr)) ? (*small_block_row_width) : block_side; *matrix_size_current_pr = (*max_rows_pp)*matrix_side; return 0; } void MPI_printUpperLeftBlock(double *a, int matrix_side, int block_side, int total_pr, int current_pr, const int *blocks_order_reversed, double *buf_string, double *buf_string_2){ double *buf = 0; double *recvbuf = 0; double *sendbuf = 0; int corner_side = 7; MPI_Status status; int i, j, real_i; int pos_i, i_proc_id; int total_block_rows, total_full_block_rows, block_size, block_string_size; int max_block_rows_pp, max_rows_pp, short_block_string_size, last_block_row_proc_id, last_block_row_in_current_pr; int small_block_row_width, small_block_size, current_pr_full_rows, last_block_row_width, matrix_size_current_pr; int corner_total_block_rows; initParameters(matrix_side, block_side, total_pr, current_pr, &total_block_rows, &total_full_block_rows, &block_size, &block_string_size, &max_block_rows_pp, &max_rows_pp, &short_block_string_size, &last_block_row_proc_id, &last_block_row_in_current_pr, &small_block_row_width, &small_block_size, &current_pr_full_rows, &last_block_row_width, &matrix_size_current_pr); buf = (double*) malloc(corner_side*block_string_size*sizeof(double)); recvbuf = buf_string; sendbuf = buf_string_2; if (matrix_side<corner_side){ corner_side = matrix_side; } corner_total_block_rows = (corner_side + block_side - 1)/block_side; //int current_pr_block_rows = (corner_total_block_rows + total_pr - 1)/total_pr; //int sendbuf_size = corner_side*block_side; for(i = 0; i < corner_total_block_rows; i++){ real_i = blocks_order_reversed[i]; //pos_i = i/total_pr; //i_proc_id = i%total_pr; pos_i = real_i/total_pr; i_proc_id = real_i%total_pr; if(i_proc_id != 0){ if(current_pr == i_proc_id){ for(j=0;j<block_string_size;j++){ sendbuf[j]=a[pos_i*block_string_size+j]; } MPI_Send(sendbuf, block_string_size, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); } if(current_pr == 0){ MPI_Recv(recvbuf, block_string_size, MPI_DOUBLE, i_proc_id, 0, MPI_COMM_WORLD, &status); for(j=0; j<block_string_size; j++){ buf[i*block_string_size+j]=recvbuf[j]; } } } else{ for(j=0; j<block_string_size; j++){ buf[i*block_string_size+j]=a[pos_i*block_string_size+j]; } } } if(current_pr==0){ printUpperLeftBlock(buf, matrix_side, block_side); } free(buf); }
C
#include "holberton.h" int prime(int n, int x); /** * prime - Entry point * @n: d * @x: d * * Return: Always 0 (Success) */ int prime(int n, int x) { if (n % x == 0 && x < n) { return (0); } else if (n % x != 0 && x < n) { return (prime(n, x + 1)); } return (1); } /** * is_prime_number - Entry point * @n: d * * * Return: Always 0 (Success) */ int is_prime_number(int n) { if (n <= 0) { return (0); } else if (n == 1) { return (0); } else { return (prime(n, 2)); } }
C
#include<stdio.h> #include<stdlib.h> int main () { int num, cont, par=0, impar=0, positivo=0, negativo = 0; for (cont=0;cont<5;cont++){ printf("Digite um numero: "); scanf("%i", &num); if(num%2 == 0) { par++; } else { impar++; } if (num>0) { positivo++; } else{ negativo++; } } printf("Total:\n %i Pares\n %i Impares\n %i Positivos\n %i Negativos", par, impar, positivo, negativo); system("pause"); return 0; }
C
#pragma once #include "labels.h" struct label* make_label_variable(char* line, int* address) { char* context = NULL; struct label* label = NULL; int asterisk = 0; int count = 1; //Sprawdź czy w linii występuje znak '*' asterisk = (strchr(line, '*') != NULL); label = malloc(sizeof(struct label)); if (label == NULL) exit(EXIT_FAILURE); line = strtok_s(line, " \t", &context); //Stwórz etykietę zmiennej strcpy_s(label->name, MAX_LABEL_SIZE, line); label->address = *address; label->reg = MEMORY_REGISTER; //Zwiększ adres o rozmiar typu integer razy ilość zmiennych if (asterisk != 0) { line = strtok_s(NULL, " DCS*\t", &context); count = atoi(line); } *address += INTEGER_SIZE * count; return label; } struct label* make_label_command(char* line, int* address) { int command = 0; int command_size = 0; int add_label = 0; char* context = NULL; struct label* label = NULL; add_label = (line[0] != ' ' && line[0] != '\t'); line = strtok_s(line, " \t", &context); //Stwórz etykietę rozkazu if (add_label != 0) { label = malloc(sizeof(struct label)); if (label == NULL) exit(EXIT_FAILURE); if (strcpy_s(label->name, MAX_LABEL_SIZE, line) != 0) { perror(""); exit(EXIT_FAILURE); } label->address = *address; label->reg = COMMAND_REGISTER; line = strtok_s(NULL, " \t", &context); } //Zwiększ adres o rozmiar rozkazu command = get_command(line); command_size = get_command_size(command); *address += command_size; if (add_label != 0) return label; return NULL; } struct label* make_labels(FILE* input, int* label_count) { char line[MAX_LINE_SIZE]; struct label* labels = NULL; struct label* labels_temp = NULL; struct label* label_temp = NULL; int memory_address = 0; int command_address = 0; //Przejdź po sekcji danych i stwórz etykiety zmiennych while (fgets(line, MAX_LINE_SIZE, input) != NULL && line[0] != '\n' && line[0] != '#') { labels_temp = realloc(labels, ++*label_count * sizeof(struct label)); if (labels_temp == NULL) exit(EXIT_FAILURE); labels = labels_temp; labels[*label_count - 1] = *make_label_variable(line, &memory_address); } //Przejdź po sekcji rozkazów i stwórz etykiety rozkazów while (fgets(line, MAX_LINE_SIZE, input) != NULL) { if (line[0] == '#') continue; //Jeśli wskaźnik na etykietę nie jest NULL dodaj etykietę label_temp = make_label_command(line, &command_address); if (label_temp != NULL) { labels_temp = realloc(labels, ++ * label_count * sizeof(struct label)); if (labels_temp == NULL) exit(EXIT_FAILURE); labels = labels_temp; labels[*label_count - 1] = *label_temp; } } //Przewiń do początku pliku rewind(input); return labels; } struct label* find_label(const char* name, struct label* labels, int label_count) { int n; for (n = 0; n < label_count; ++n) if (strcmp(name, labels[n].name) == 0) //Porównaj nazwę zmiennej z podaną nazwą return &labels[n]; fprintf(stderr, "Etykieta %s nie istnieje!", name); exit(EXIT_FAILURE); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kmarques <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/09 19:19:31 by kmarques #+# #+# */ /* Updated: 2021/08/18 12:29:10 by kmarques ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /** * @brief Apply function to the list and return a new list * * @param lst First element * @param f Function * @param del Delete function * @return t_list* New list */ t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)) { t_list *element; t_list *newlst; newlst = NULL; while (lst != NULL) { element = ft_lstnew(f(lst->content)); if (element == NULL) { ft_lstclear(&newlst, del); return (NULL); } ft_lstadd_back(&newlst, element); lst = lst->next; } return (newlst); }
C
/* recognizeExp.c, Gerard Renardel, 29 January 2014 * * In this file a recognizer acceptExpression is definined that can recognize * arithmetical expressions generated by the following BNF grammar: * * <expression> ::= <term> { '+' <term> | '-' <term> } * * <term> ::= <factor> { '*' <factor> | '/' <factor> } * * <factor> ::= <number> | <identifier> | '(' <expression> ')' * * Input for the recognizer is the token list constructed by the scanner (in scanner.c). * For the recognition of a token list the method of *recursive descent* is used. * It relies on the use of three functions for the recognition and processing of * terms, factors and expressions, respectively. * These three functions are defined with mutual recursion, corresponding with the * structure of the BNF grammar. */ #include <stdio.h> /* getchar, printf */ #include <stdlib.h> /* NULL */ #include "scanner.h" #include "recognizeEq.h" #include <math.h> #include <string.h> /* The functions acceptNumber, acceptIdentifier and acceptCharacter have as * (first) argument a pointer to an token list; moreover acceptCharacter has as * second argument a character. They check whether the first token * in the list is a number, an identifier or the given character, respectively. * When that is the case, they yield the value 1 and the pointer points to the rest of * the token list. Otherwise they yield 0 and the pointer remains unchanged. */ int acceptNumber(List *lp) { if (*lp != NULL && (*lp)->tt == Number) { *lp = (*lp)->next; return 1; } return 0; } int acceptIdentifier(List *lp) { if (*lp != NULL && (*lp)->tt == Identifier) { *lp = (*lp)->next; return 1; } return 0; } int acceptCharacter(List *lp, char c) { if (*lp != NULL && (*lp)->tt == Symbol && ((*lp)->t).symbol == c) { *lp = (*lp)->next; return 1; } return 0; } /* The functions acceptFactor, acceptTerm and acceptExpression have as * argument a pointer to a token list. They check whether the token list * has an initial segment that can be recognized as factor, term or expression, respectively. * When that is the case, they yield the value 1 and the pointer points to the rest of * the token list. Otherwise they yield 0 and the pointer remains unchanged. */ // stores the biggest exponent int biggestExponent = - 1; // reads the value of the number and determine whether it is biggest exponent int valueNumber(List *lp, double *wp) { if (*lp != NULL && (*lp)->tt == Number) { *wp = ((*lp)->t).number; *lp = (*lp)->next; // if the value of the number is bigger than set it as the biggestExponent if (*wp > biggestExponent) { biggestExponent = *wp; } return 1; } return 0; } // accepts exponent '^' character and a natural number succeeding it int acceptExponent(List *lp) { double wp = 0; // checks whether there is an exponent if (acceptCharacter(lp, '^')) { // only accepts natural numbers if (acceptCharacter(lp, '-')) { return 0; } else { // calls the valueNumber to determine the value of the exponent return valueNumber(lp, &wp); } } else { biggestExponent = 1; return 1; } return 0; } // accepts terms in the form of <nat> | [ <nat>] <identifier> ['^' <nat>] int acceptTerm(List *lp) { if (acceptNumber(lp)) { if (acceptIdentifier(lp)) { // if number and identifier then call acceptExponent to check whether there is an exponent return acceptExponent(lp); } return 1; } else { if (acceptIdentifier(lp)) { // if there is only identifier then check whether an exponent is inputted return acceptExponent(lp); } return 0; } return 0; } // accepts expressions of the form ['-'] <term> {'+' <term> | '-' <term>} int acceptExpression(List *lp) { // checks whether it is a negative number if (acceptCharacter(lp, '-')) { // checks whether it is a valid term if (!acceptTerm(lp)) { return 0; } } else if (!acceptTerm(lp)) { return 0; } while (acceptCharacter(lp, '+') || acceptCharacter(lp, '-')) { // checks whether it is a valid term if (!acceptTerm(lp)) { return 0; } } /* no + or -, so we reached the end of the expression */ return 1; } // accepts equations of the the form <expression> '=' <expression> int acceptEquation(List *lp) { return (acceptExpression(lp) && acceptCharacter(lp,'=') && acceptExpression(lp)); } // determines the amount of variables there are. returns 1 if there is 1 variable int determineVariables(List lp) { // initialise string to store the value of the identifiers/variables char *string = NULL; // loop through list while (lp != NULL) { if (lp->tt == Identifier) { if (string == NULL) { free(string); string = (lp)->t.identifier; } // conditional to compare whether the variable stored is the same if (strcmp(string, lp->t.identifier)) { return 2; } } if (lp != NULL) { lp = (lp)->next; } } // if there are no variables if (string == NULL) { return 0; } return 1; } /* The function recognizeExpressions demonstrates the recognizer. */ void recognizeEquations() { char *ar; List tl, tl1; printf("give an equation: "); ar = readInput(); while (ar[0] != '!') { tl = tokenList(ar); printList(tl); tl1 = tl; if (acceptEquation(&tl1) && tl1 == NULL) { // conditional if there is one variable if (determineVariables(tl) == 1) { printf("this is an equation in 1 variable"); printf("%s %s %d\n", " of", "degree", biggestExponent); // resets the biggestExponent biggestExponent = -1; } // conditional if there are more than 1 variable else if (determineVariables(tl) != 1) { printf("this is an equation, but not in 1 variable\n"); } } else { printf("this is not an equation\n"); } free(ar); freeTokenList(tl); printf("\ngive an equation: "); ar = readInput(); } free(ar); printf("good bye\n"); }
C
#include <stdio.h> int fib(int i){ if(i==1) { return 1; } else { if(i==2) { return 1; } else { return fib(i-1)+fib(i-2); } } } int main(void) { int i; scanf("%d",&i); printf("Resultado = %d\n",fib(i)); return 0; }
C
/* * Copyright (c) 2007 - 2014 Joseph Gaeddert * * This file is part of liquid. * * liquid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * liquid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with liquid. If not, see <http://www.gnu.org/licenses/>. */ // // asgram (ASCII spectrogram) // #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <complex.h> #include "liquid.internal.h" struct ASGRAM(_s) { unsigned int nfft; // transform size SPGRAM() periodogram; // spectral periodogram object TC * X; // spectral periodogram output float * psd; // power spectral density float levels[10]; // threshold for signal levels char levelchar[10]; // characters representing levels unsigned int num_levels; // number of levels float scale; // dB per division float offset; // dB offset (max) }; // create asgram object with size _nfft ASGRAM() ASGRAM(_create)(unsigned int _nfft) { // validate input if (_nfft < 2) { LOGE("error: asgram%s_create(), fft size must be at least 2\n", EXTENSION); exit(1); } // create main object ASGRAM() q = (ASGRAM()) malloc(sizeof(struct ASGRAM(_s))); q->nfft = _nfft; // allocate memory for PSD estimate q->X = (TC * ) malloc((q->nfft)*sizeof(TC) ); q->psd = (float *) malloc((q->nfft)*sizeof(float)); // create spectral periodogram object unsigned int window_len = q->nfft; float beta = 10.0f; q->periodogram = SPGRAM(_create_kaiser)(q->nfft, window_len, beta); // power spectral density levels q->num_levels = 10; q->levelchar[9] = '#'; q->levelchar[8] = 'M'; q->levelchar[7] = 'N'; q->levelchar[6] = '&'; q->levelchar[5] = '*'; q->levelchar[4] = '+'; q->levelchar[3] = '-'; q->levelchar[2] = ','; q->levelchar[1] = '.'; q->levelchar[0] = ' '; ASGRAM(_set_scale)(q, 0.0f, 10.0f); return q; } // destroy asgram object void ASGRAM(_destroy)(ASGRAM() _q) { // destroy spectral periodogram object SPGRAM(_destroy)(_q->periodogram); // free PSD estimate array free(_q->X); free(_q->psd); // free main object memory free(_q); } // resets the internal state of the asgram object void ASGRAM(_reset)(ASGRAM() _q) { SPGRAM(_reset)(_q->periodogram); } // set scale and offset for spectrogram // _q : asgram object // _offset : signal offset level [dB] // _scale : signal scale [dB] void ASGRAM(_set_scale)(ASGRAM() _q, float _offset, float _scale) { if (_scale <= 0.0f) { LOGE("ASGRAM(_set_scale)(), scale must be greater than zero\n"); exit(1); } _q->offset = _offset; _q->scale = _scale; unsigned int i; for (i=0; i<_q->num_levels; i++) _q->levels[i] = _q->offset + i*_q->scale; } // push a single sample into the asgram object // _q : asgram object // _x : input buffer [size: _n x 1] // _n : input buffer length void ASGRAM(_push)(ASGRAM() _q, TI _x) { // push sample into internal spectral periodogram SPGRAM(_push)(_q->periodogram, _x); } // write a block of samples to the asgram object // _q : asgram object // _x : input buffer [size: _n x 1] // _n : input buffer length void ASGRAM(_write)(ASGRAM() _q, TI * _x, unsigned int _n) { // write samples to internal spectral periodogram SPGRAM(_write)(_q->periodogram, _x, _n); } // compute spectral periodogram output from current buffer contents // _q : ascii spectrogram object // _ascii : character buffer [size: 1 x n] // _peakval : value at peak (returned value) // _peakfreq : frequency at peak (returned value) void ASGRAM(_execute)(ASGRAM() _q, char * _ascii, float * _peakval, float * _peakfreq) { // execute spectral periodogram SPGRAM(_execute)(_q->periodogram, _q->X); // compute PSD magnitude and apply FFT shift unsigned int i; for (i=0; i<_q->nfft; i++) _q->psd[i] = 10*log10f(cabsf(_q->X[(i + _q->nfft/2)%_q->nfft])); unsigned int j; for (i=0; i<_q->nfft; i++) { // find peak if (i==0 || _q->psd[i] > *_peakval) { *_peakval = _q->psd[i]; *_peakfreq = (float)(i) / (float)(_q->nfft) - 0.5f; } // determine ascii level (which character to use) #if 0 for (j=0; j<_q->num_levels-1; j++) { if ( _q->psd[i] > ( _q->offset - j*(_q->scale)) ) break; } _ascii[i] = _q->levelchar[j]; #else _ascii[i] = _q->levelchar[0]; for (j=0; j<_q->num_levels; j++) { if ( _q->psd[i] > _q->levels[j] ) _ascii[i] = _q->levelchar[j]; } #endif } // append null character to end of string //_ascii[i] = '\0'; } // compute spectral periodogram output from current buffer // contents and print standard format to stdout void ASGRAM(_print)(ASGRAM() _q) { float maxval; float maxfreq; char ascii[_q->nfft+1]; ascii[_q->nfft] = '\0'; // append null character to end of string // execute the spectrogram ASGRAM(_execute)(_q, ascii, &maxval, &maxfreq); // print the spectrogram to stdout LOGI(" > %s < pk%5.1f dB [%5.2f]\n", ascii, maxval, maxfreq); }
C
#include <stdio.h> unsigned mulinv_euclid(d){ // d must be odd. unsigned x1, v1, x2, v2, x3, v3, q; x1= 0xFFFFFFFF; v1 = -d; x2 = 1; v2 = d; while (v2 > 1){ q = v1/v2; x3 = x1 - q*x2; v3 = v1 - q*v2; x2 = x3; v2 = v3; } return x2; } unsigned mulinv_newton(unsigned d){ // d must be odd. unsigned xn, t; xn = d; loop: t = d*xn; if(t == 1) return xn; xn = xn*(2 - t); goto loop; }
C
// // Exercise2-17 // // Created by Greg Tosato on 8/11/18. // Copyright © 2018 Dingo Byte Solutions. All rights reserved. // // This program prints the numbers 1-4 using various methods. #include <stdio.h> void exercise2_17(void) { int num1 = 1, num2 = 2, num3 = 3, num4 = 4; printf("The numbers are 1, 2, 3, 4\n"); printf("The numbers are %d, %d, %d, %d\n", num1, num2, num3, num4); printf("The numbers are %d, ", num1); printf("%d, ", num2); printf("%d, ", num3); printf("%d\n\n", num4); }
C
#include <stdio.h> struct student { char name[10]; int roll; }; void display(struct student stu); // function prototype should be below to the structure declaration otherwise compiler shows error int main() { struct student stud; printf("Enter student's name: "); scanf ("%[^\n]%*c", stud.name); printf("Enter roll number:"); // fflush(stdin); scanf("%d", &stud.roll); display(stud); // passing structure variable stud as argument return 0; } void display(struct student stu){ printf("Output\nName: %s",stu.name); printf("\nRoll: %d",stu.roll); }
C
#include "delay.h" void init__delay(void){ RCC_ClocksTypeDef RCC_clocks; RCC_GetClocksFreq(&RCC_clocks); SysTick_Config(RCC_clocks.HCLK_Frequency/100000); } void _delay_ms(int ms){ sysTickCounter = 100 * ms; while (sysTickCounter != 0); } void SysTick_Handler(void) { if(sysTickCounter != 0) sysTickCounter--; }
C
#include <stdio.h> int global = 2; int global_un; int main() { int i = 0, sum = 0, *p; char * string = "Nyat!"; char temp[1000]; FILE *fp = fopen("/proc/self/maps", "r"); printf("address of const string %p\n",string); printf("address of local variable %p\n",&i); printf("address of initialized global %p\n",&global); printf("address of uninitialized global variable %p\n",&global_un); printf("address of main %p\n",&main); while(fgets(temp, sizeof(temp)/sizeof(temp[0]), fp)) { printf("%s",temp); } }
C
#ifndef FINISHEDGAMEDATA_H #define FINISHEDGAMEDATA_H #include <QMetaType> #include <QTime> struct FinishedGameData { int nbStars; QTime bestTime; bool hasSomethingBetterThan(const FinishedGameData& other) const { return nbStars > other.nbStars || (bestTime.isValid() && !other.bestTime.isValid()) || bestTime < other.bestTime; } static FinishedGameData getBestOfTwo(const FinishedGameData& lhs, const FinishedGameData& rhs) { FinishedGameData result; result.nbStars = qMax(lhs.nbStars, rhs.nbStars); if (!lhs.bestTime.isValid()) result.bestTime = rhs.bestTime; else if (!rhs.bestTime.isValid()) result.bestTime = lhs.bestTime; else result.bestTime = qMin(lhs.bestTime, rhs.bestTime); return result; } }; inline bool operator==(const FinishedGameData& lhs, const FinishedGameData& rhs) { return lhs.nbStars == rhs.nbStars && lhs.bestTime == rhs.bestTime; } inline bool operator!=(const FinishedGameData& lhs, const FinishedGameData& rhs) { return !(lhs == rhs); } QDebug operator<<(QDebug dbg, const FinishedGameData& obj); Q_DECLARE_METATYPE(FinishedGameData) #endif // FINISHEDGAMEDATA_H
C
#include <stdio.h> #include <stdlib.h> /* <ul>Function returnPointerArray: <li>Arguments: [1] an array of ints and [2] an array length <li>Malloc’s an int* array of the same element length <li>Initializes each element of the newly-allocated array to point to the corresponding element of the passed-in array <li>Returns a pointer to the newly-allocated array */ int** returnPointerArray(int a[], int length){ int **b = malloc(length * sizeof(int*)); for(int i = 0; i < length; ++i){ b[i] = &a[i]; } return b; } int main(int argc, char **argv){ int a[] = {1, 2, 3}; int **b = returnPointerArray(a, 3); for(int i = 0; i < 3; ++i){ printf("%d\n", *b[i]); } free(b); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "pca.h" #include <math.h> float norm2(float **a, int n, int m) { int i, j; float accum = 0.0; for(i=1; i<=n; i++) { for(j=1; j<=m; j++) { accum += a[i][j] * a[i][j]; } } return sqrt(accum); } float frand() { return ((float) rand()) / ((float) RAND_MAX) * 2.0 - 1.0; } int main(int argc, char *argv[]) { float **A, **E, **SUM; float *evals, *interm; float Enorm; int i, j; srand(time(NULL)); A = matrix(2, 2); E = matrix(2, 2); SUM = matrix(2, 2); evals = vector(2); /* Storage alloc. for vector of eigenvalues */ interm = vector(2); /* Storage alloc. for 'intermediate' vector */ float sA[2][2] = {{6.8, 2.4}, {2.4, 8.2}}; float sE[2][2] = {{.002, .003}, {.003, .001}}; for (i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { A[i+1][j+1] = sA[i][j]; if(i >= j) E[i+1][j+1] = frand() * 0.005; } } for (i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { if(i < j) E[i+1][j+1] = E[j+1][i+1]; } } for (i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { SUM[i+1][j+1] = A[i+1][j+1] + E[i+1][j+1]; } } Enorm = norm2(E, 2, 2); printf("Matrix A:\n"); print_matrix(A, 2, 2); printf("Matrix E:\n"); print_matrix(E, 2, 2); printf("Matrix E norm2 = %f:\n", Enorm); printf("Matrix SUM:\n"); print_matrix(SUM, 2, 2); printf("Householder tridiagonalization\n"); tred2(SUM, 2, evals, interm); /* Triangular decomposition */ printf("diagonal:\n"); print_vector(evals, 2); printf("off-diagonal:\n"); print_vector(interm, 2); printf("Q:\n"); print_matrix(SUM, 2, 2); printf("Implicit QR diagonalization\n"); tqli(evals, interm, 2, SUM); /* Reduction of sym. trid. matrix */ printf("Eigenvalues:\n"); for (j = 2; j >= 1; j--) { printf("%60.50f\n", evals[j]); } /* double eigs[] = { 4.998759651901539591278833540854975581169128417968750, 10.0042403480984596342295844806358218193054199218750 };*/ double eigs[] = { 5.0, 10.0 }; double eigerr; printf("Error in eigenvalues: (should be <= %f)\n", Enorm); for (j = 2; j >= 1; j--) { eigerr = eigs[j-1] - ((double) evals[j]); printf("%20.10G", eigerr); if(eigerr > Enorm) printf(" <- ERROR, eigenvalue exeeds maximum"); printf("\n"); } free_vector(interm, 2); free_vector(evals, 2); free_matrix(SUM, 2, 2); free_matrix(E, 2, 2); free_matrix(A, 2, 2); return 0; }
C
#include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <limits.h> #include <stdio.h> #include <string.h> #define MAX_BUF 1024 int main() { int fd, ret; char buf[MAX_BUF]; char * myfifo = "/tmp/myserverfifo"; /* write PID to the FIFO */ fd = open(myfifo, O_WRONLY); sprintf(buf, "%d", getpid()); if( write(fd, buf, sizeof(buf)) < 0) fprintf(stderr, "Error\n"); close(fd); return 0; }
C
/* mosiscrc -- calculate and print POSIX.2 checksums and sizes of text or binary files. This file is a modified version of the file "cksum.c" from GNU textutils version 1.22. The changes were made on October 27, 1999. It packages most of what that program did into a single file, for ease of compilation, with some changes. The changes cause the program to work differently for text files than for binary files. Use the -b option to compute a checksum on a binary file and the -t option to compute a checksum on a text file. MOSIS customers who need to compute the CRC checksum of a text file (e.g., CIF file) must use this program. The standard GNU cksum program will NOT give the checksum MOSIS expects for a text file. MOSIS customers who need to compute the CRC checksum of a binary file (e.g., GDS file) can use either the standard GNU cksum program or this program since they both compute identical checksums. The MOSIS CRC checksum for a text file uses the same CRC computation as the standard GNU cksum program, but applies it to a different set of characters. The differences are: 1. Every contiguous sequence of characters with value <= ASCII space (32) is treated as a single space character. 2. There is an implied leading and trailing space character in every file. These changes make the checksum for a text file insensitive to differences in end of line conventions (CR LF versus LF) and insensitive to control characters and white space that may be added by mailers. To compile and run this checksum program: For Unix (using GNU C compiler): % gcc -O2 -o mosiscrc mosiscrc.c % mosiscrc -h [To get help] % mosiscrc -t your-layout-file [For a CIF file] % mosiscrc -b your-layout-file [For a GDS file] For VMS: $ cc mosiscrc.c $ define lnk$library sys$library:vaxcrtl.olb $ link mosiscrc.obj $ mosiscrc :== $your-disk:[your-full-directory-path]mosiscrc.exe $ mosiscrc -h [To get help] $ mosiscrc -t your-layout-file [For a CIF file] $ mosiscrc -b your-layout-file [For a GDS file] */ /* cksum -- calculate and print POSIX.2 checksums and sizes of files Copyright (C) 92, 95, 1996 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Written by Q. Frank Xia, [email protected]. Cosmetic changes and reorganization by David MacKenzie, [email protected]. Usage: cksum [file...] The code segment between "#ifdef CRCTAB" and "#else" is the code which calculates the "crctab". It is included for those who want verify the correctness of the "crctab". To recreate the "crctab", do following: cc -DCRCTAB -o crctab cksum.c crctab > crctab.h As Bruce Evans pointed out to me, the crctab in the sample C code in 4.9.10 Rationale of P1003.2/D11.2 is represented in reversed order. Namely, 0x01 is represented as 0x80, 0x02 is represented as 0x40, etc. The generating polynomial is crctab[0x80]=0xedb88320 instead of crctab[1]=0x04C11DB7. But the code works only for a non-reverse order crctab. Therefore, the sample implementation is wrong. This software is compatible with neither the System V nor the BSD `sum' program. It is supposed to conform to P1003.2/D11.2, except foreign language interface (4.9.5.3 of P1003.2/D11.2) support. Any inconsistency with the standard except 4.9.5.3 is a bug. */ #ifdef CRCTAB #include <stdio.h> #define BIT(x) ( (unsigned long)1 << (x) ) #define SBIT BIT(31) /* The generating polynomial is 32 26 23 22 16 12 11 10 8 7 5 4 2 1 G(X)=X + X + X + X + X + X + X + X + X + X + X + X + X + X + 1 The i bit in GEN is set if X^i is a summand of G(X) except X^32. */ #define GEN (BIT(26)|BIT(23)|BIT(22)|BIT(16)|BIT(12)|BIT(11)|BIT(10)\ |BIT(8) |BIT(7) |BIT(5) |BIT(4) |BIT(2) |BIT(1) |BIT(0)); static unsigned long r[8]; static void fill_r () { int i; r[0] = GEN; for (i = 1; i < 8; i++) r[i] = (r[i - 1] & SBIT) ? (r[i - 1] << 1) ^ r[0] : r[i - 1] << 1; } static unsigned long remainder (m) int m; { unsigned long rem = 0; int i; for (i = 0; i < 8; i++) if (BIT (i) & m) rem = rem ^ r[i]; return rem & 0xFFFFFFFF; /* Make it run on 64-bit machine. */ } int main () { int i; fill_r (); printf ("unsigned long crctab[256] = {\n 0x0"); for (i = 0; i < 51; i++) { printf (",\n 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X", remainder (i * 5 + 1), remainder (i * 5 + 2), remainder (i * 5 + 3), remainder (i * 5 + 4), remainder (i * 5 + 5)); } printf ("\n};\n"); exit (0); } #else /* !CRCTAB */ #include <stdio.h> #include <sys/types.h> #include <string.h> /* Number of bytes to read at once. */ #define BUFLEN (1 << 16) /* Mode for opening binary file for read. */ #ifndef WIN32 #define READ_MODE "r" #else #define READ_MODE "rb" #endif /* The name this program was run with. */ char *program_name; static unsigned long const crctab[256] = { 0x0, 0x04C11DB7, 0x09823B6E, 0x0D4326D9, 0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005, 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61, 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD, 0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9, 0x5F15ADAC, 0x5BD4B01B, 0x569796C2, 0x52568B75, 0x6A1936C8, 0x6ED82B7F, 0x639B0DA6, 0x675A1011, 0x791D4014, 0x7DDC5DA3, 0x709F7B7A, 0x745E66CD, 0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039, 0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5, 0xBE2B5B58, 0xBAEA46EF, 0xB7A96036, 0xB3687D81, 0xAD2F2D84, 0xA9EE3033, 0xA4AD16EA, 0xA06C0B5D, 0xD4326D90, 0xD0F37027, 0xDDB056FE, 0xD9714B49, 0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95, 0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1, 0xE13EF6F4, 0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D, 0x34867077, 0x30476DC0, 0x3D044B19, 0x39C556AE, 0x278206AB, 0x23431B1C, 0x2E003DC5, 0x2AC12072, 0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16, 0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA, 0x7897AB07, 0x7C56B6B0, 0x71159069, 0x75D48DDE, 0x6B93DDDB, 0x6F52C06C, 0x6211E6B5, 0x66D0FB02, 0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1, 0x53DC6066, 0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA, 0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E, 0xBFA1B04B, 0xBB60ADFC, 0xB6238B25, 0xB2E29692, 0x8AAD2B2F, 0x8E6C3698, 0x832F1041, 0x87EE0DF6, 0x99A95DF3, 0x9D684044, 0x902B669D, 0x94EA7B2A, 0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E, 0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2, 0xC6BCF05F, 0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686, 0xD5B88683, 0xD1799B34, 0xDC3ABDED, 0xD8FBA05A, 0x690CE0EE, 0x6DCDFD59, 0x608EDB80, 0x644FC637, 0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB, 0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F, 0x5C007B8A, 0x58C1663D, 0x558240E4, 0x51435D53, 0x251D3B9E, 0x21DC2629, 0x2C9F00F0, 0x285E1D47, 0x36194D42, 0x32D850F5, 0x3F9B762C, 0x3B5A6B9B, 0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF, 0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623, 0xF12F560E, 0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7, 0xE22B20D2, 0xE6EA3D65, 0xEBA91BBC, 0xEF68060B, 0xD727BBB6, 0xD3E6A601, 0xDEA580D8, 0xDA649D6F, 0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3, 0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7, 0xAE3AFBA2, 0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B, 0x9B3660C6, 0x9FF77D71, 0x92B45BA8, 0x9675461F, 0x8832161A, 0x8CF30BAD, 0x81B02D74, 0x857130C3, 0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640, 0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C, 0x7B827D21, 0x7F436096, 0x7200464F, 0x76C15BF8, 0x68860BFD, 0x6C47164A, 0x61043093, 0x65C52D24, 0x119B4BE9, 0x155A565E, 0x18197087, 0x1CD86D30, 0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC, 0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088, 0x2497D08D, 0x2056CD3A, 0x2D15EBE3, 0x29D4F654, 0xC5A92679, 0xC1683BCE, 0xCC2B1D17, 0xC8EA00A0, 0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB, 0xDBEE767C, 0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18, 0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4, 0x89B8FD09, 0x8D79E0BE, 0x803AC667, 0x84FBDBD0, 0x9ABC8BD5, 0x9E7D9662, 0x933EB0BB, 0x97FFAD0C, 0xAFB010B1, 0xAB710D06, 0xA6322BDF, 0xA2F33668, 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4 }; /* Nonzero if any of the files read were the standard input. */ static int have_read_stdin; /* Calculate and print the checksum and length in bytes of file FILE, or of the standard input if FILE is "-". If PRINT_NAME is nonzero, print FILE next to the checksum and size. TEXT indicates whether file is text or binary. Return 0 if successful, -1 if an error occurs. */ static int cksum (char *file, int print_name, int text) { unsigned char buf[BUFLEN]; unsigned long crc = 0; long length = 0; long high_bits = 0; long controls = 0; long bytes_read; register FILE *fp; int insep; /* Are we in a separator sequence? */ unsigned char c; if (!strcmp (file, "-")) { fp = stdin; have_read_stdin = 1; } else { fp = fopen (file, READ_MODE); if (fp == NULL) { fprintf (stderr, "%s: cannot open input file %s\n", program_name, file); fflush(stderr); return -1; } } if (text) { /* Process implied leading space character */ length = 1; insep = 1; crc = (crc << 8) ^ crctab[((crc >> 24) ^ (unsigned char) 32) & 0xFF]; while ((bytes_read = fread (buf, 1, BUFLEN, fp)) > 0) { unsigned char *cp = buf; while (bytes_read--) { c = *(cp++); if (c >= 128) { high_bits++; } else if (c < ' ') { switch (c) { case '\t': case '\n': case '\r': case '\f': break; default: controls++; } } if (c > ' ') { crc = (crc << 8) ^ crctab[((crc >> 24) ^ c) & 0xFF]; length++; insep = 0; } else if (!insep) { crc = (crc << 8) ^ crctab[((crc >> 24) ^ (unsigned char) 32) & 0xFF]; length++; insep = 1; } } } /* Add implied trailing space character, if needed */ if (!insep) { crc = (crc << 8) ^ crctab[((crc >> 24) ^ (unsigned char) 32) & 0xFF]; length++; } } else { /* Binary file */ while ((bytes_read = fread (buf, 1, BUFLEN, fp)) > 0) { unsigned char *cp = buf; length += bytes_read; while (bytes_read--) { c = *(cp++); if (c >= 128) { high_bits++; } else if (c < ' ') { switch (c) { case '\t': case '\n': case '\r': case '\f': break; default: controls++; } } crc = (crc << 8) ^ crctab[((crc >> 24) ^ c) & 0xFF]; } } } if (ferror (fp)) { fprintf (stderr, "%s: error reading file %s\n", program_name, file); fflush(stderr); if (strcmp (file, "-")) fclose (fp); return -1; } if (strcmp (file, "-") && fclose (fp) == EOF) { fprintf (stderr, "%s: error closing file %s\n", program_name, file); fflush(stderr); return -1; } bytes_read = length; while (bytes_read > 0) { crc = (crc << 8) ^ crctab[((crc >> 24) ^ bytes_read) & 0xFF]; bytes_read >>= 8; } crc = ~crc & 0xFFFFFFFF; printf ("CRC-Checksum: %lu %ld", crc, length); if (print_name) printf (" %s", file); putchar ('\n'); fflush(stdout); if (text && (controls != 0 || high_bits != 0)) { fprintf (stderr, "\n%s: file has %ld control characters and %ld high bit characters\n", program_name, controls, high_bits); fprintf (stderr, "%s: file %s may not be a text file\n", program_name, file); fprintf (stderr, "%s: you may need to use -b option instead of -t\n\n", program_name); fflush(stderr); } else if (!text && controls == 0 && high_bits == 0) { fprintf (stderr, "\n%s: file has no control characters or high bit characters\n", program_name); fprintf (stderr, "%s: file %s may not be a binary file\n", program_name, file); fprintf (stderr, "%s: you may need to use -t option instead of -b\n\n", program_name); fflush(stderr); } return 0; } static void usage (void) { printf ("\nUsage: %s OPTIONS [FILE]...\n", program_name); printf ("Print CRC checksum and byte count of each FILE.\nRead from standard input if no files named.\nOptions:\n -b input files are binary files (GDS)\n -t input files are text files (CIF)\n -h display this help and exit\n\n"); fflush(stdout); } /* Pause until get input from user on Windows, so program output remains visible. */ void pause_for_input (void) { #ifdef WIN32 char buffer[100]; printf ("\nPress Enter to exit: "); fflush(stdout); fgets(buffer, 100, stdin); #endif } int main (int argc, char **argv) { int i; int errors = 0; int optind; int text, binary; program_name = "mosiscrc"; have_read_stdin = 0; text = 0; binary = 0; optind = 1; while (optind < argc) { if (argv[optind][0] != '-') break; switch (argv[optind][1]) { case 'b': binary = 1; break; case 't': text = 1; break; case 'h': case 'H': usage(); pause_for_input(); return(1); break; default: usage(); pause_for_input(); return(1); } optind++; } if (!binary && !text) { fprintf (stderr, "%s: must specify either -b or -t option (binary or text)\n Try -h option for more detailed help\n", program_name); fflush(stderr); pause_for_input(); return(1); } else if (binary && text) { fprintf (stderr, "%s: cannot specify both -b and -t options\n Try -h option for more detailed help\n", program_name); fflush(stderr); pause_for_input(); return(1); } if (optind >= argc) { if (cksum ("-", 0, text) < 0) errors = 1; } else { for (i = optind; i < argc; i++) if (cksum (argv[i], 1, text) < 0) errors = 1; } printf("\n"); printf("NOTE: The CRC-Checksum consists of two numbers. If you submit your project\n"); printf("via the web, both numbers must be entered in the Fabricate web form.\n"); printf("The first number must be entered in the Checksum field.\n"); printf("The second number must be entered in the Count field.\n"); printf("\n"); if (have_read_stdin && fclose (stdin) == EOF) { fprintf (stderr, "%s: error closing standard input\n", program_name); fflush(stderr); errors = 1; } pause_for_input(); return (errors == 0 ? 0 : 1); } #endif /* !CRCTAB */
C
#include<stdio.h> #include<string.h> #include<conio.h> void main() { char str[90],i,l; scanf("%s ",&str); l=strlen(str); for(i=l-1;i>=0;i--) { printf("%c",str[i]); } }
C
#include "uls.h" static char *make_error_message(char *dirname) { char *error_message = mx_strnew( mx_strlen(dirname) + mx_strlen(strerror(errno)) + 8); mx_strcat(error_message, "uls: "); mx_strcat(error_message, dirname); mx_strcat(error_message, ": "); mx_strcat(error_message, strerror(errno)); mx_strcat(error_message, "\n"); return error_message; } static void open_error(t_file **list, char *dirname, int *flags) { char *filename = mx_memrchr(dirname, '/', mx_strlen(dirname)); char *error_message = make_error_message(filename + 1); t_file *err = mx_create_file("", ""); err->error = error_message; mx_lst_add_file(list, err); *flags |= ERROR; } t_list *mx_process_args(char *argv[], t_file **files, t_file **dirs, int *flags) { DIR *d = NULL; t_list *errors = NULL; t_file *dir_ptr = NULL; while (*argv) { (d = opendir(*argv)) ? mx_lst_add_file(dirs, mx_create_file(*argv, *argv)) : (void)0; !d ? mx_handle_nonexistent(*argv, &errors, files, dirs) : (void)0; d ? closedir(d) : 0; ++argv; } (!*dirs && !errors && !*files) ? mx_lst_add_file(dirs, mx_create_file(".", ".")) : (void)0; dir_ptr = *dirs; while (dir_ptr) { mx_explore_path(dir_ptr->name, flags, &dir_ptr->subdirs); dir_ptr = dir_ptr->next; } return errors; } void mx_handle_nonexistent(char *dirname, t_list **errors, t_file **files, t_file **dirs) { t_stat stat; t_file *file = NULL; if (lstat(dirname, &stat) == -1) mx_push_front(errors, make_error_message(dirname)); else if (!MX_ISDIR(stat.st_mode)) { file = mx_create_file(dirname, dirname); mx_lst_add_file(files, file); } else { file = mx_create_file(dirname, dirname); file->error = make_error_message(dirname); mx_lst_add_file(dirs, file); } } void mx_explore_path(char *dirname, int *flags, t_file **list) { DIR *d = opendir(dirname); t_dirent *entry = NULL; !d ? open_error(list, dirname, flags) : (void)0; while (d && (entry = readdir(d))) { if (entry->d_name[0] == '.' && !(*flags & LS_AA) && !(*flags & LS_A)) continue; else if ((!mx_strcmp(entry->d_name, ".") || !mx_strcmp(entry->d_name, "..")) && !(*flags & LS_A)) { continue; } t_file *file = mx_create_file(entry->d_name, dirname); mx_lst_add_file(list, file); (MX_ISDIR(file->st_mode) && (*flags & LS_RR) && (mx_strcmp(file->name, "..") && mx_strcmp(file->name, "."))) ? mx_explore_path(file->full_path, flags, &file->subdirs) : (void)0; } d ? closedir(d) : 0; }
C
/* * Routines for dealing with processes. */ #include "cxtk.h" #include "kernel.h" #include "ksh.h" #include "slab.h" #include "socket.h" #include "string.h" #include "wait.h" #include "mm.h" #include "config.h" struct list_head process_list; struct process *current = NULL; struct slab *proc_slab; static uint32_t pid = 1; struct process *idle_process = NULL; bool preempt_enabled = true; const char nopreempt_begin; const char nopreempt_end; #define stack_size 4096 struct static_binary { void *start; void *end; char *name; }; struct static_binary binaries[] = { { .start = process_salutations_start, .end = process_salutations_end, .name = "salutations" }, { .start = process_hello_start, .end = process_hello_end, .name = "hello" }, { .start = process_ush_start, .end = process_ush_end, .name = "ush" }, }; bool timer_can_reschedule(struct ctx *ctx) { /* Can only reschedule if we are in a timer interrupt */ if ((get_cpsr() & ARM_MODE_MASK) != ARM_MODE_IRQ) { return false; } /* Some functions are in the .nopreempt section, and should never be * preempted */ if (ctx->ret >= (uint32_t)&nopreempt_begin && ctx->ret < (uint32_t)&nopreempt_end) { return false; } return preempt_enabled; } /** * Create a process. * * The returned process resides in the current address space, and has a stack of * 4096 bytes (minus the space reserved for the process struct itself). You can * take this process and either start it using start_process(), or context * switch it in later. */ struct process *create_process(uint32_t binary) { uint32_t size, i, *dst, *src; struct process *p = slab_alloc(proc_slab); /* * Allocate a kernel stack. */ p->kstack = kmem_get_pages(PAGE_SIZE, 0) + PAGE_SIZE; /* * Determine the size of the "process image" rounded to a whole page */ size = ( /* subtract start from end */ (uint32_t)binaries[binary].end - (uint32_t)binaries[binary].start /* object file doesn't include stack space, so we assume 8 bytes * of alignment and a page of stack */ + PAGE_SIZE + 8); size = ((size >> PAGE_BITS) + 1) << PAGE_BITS; /* * Create an allocator for the user virtual memory space */ p->vmem_allocator = kmem_get_pages(PAGE_SIZE, 0); init_page_allocator(p->vmem_allocator, 0x00001000, CONFIG_KERNEL_START - 1); /* * Allocate a first-level page table. * TODO: we should only need half of one, since we're only doing half of * the page table. */ p->first = kmem_get_pages(0x4000, 14); p->ttbr0 = kvtop(p->first); for (i = 0; i < 0x2000; i++) /* one day I'll implement memset() */ p->first[i] = 0; /* * Allocate physical memory for the process image, and map it * temporarily into kernel memory. */ p->image = kmem_get_pages(size, 0); /* * Copy the "process image" over. */ dst = (uint32_t *)p->image; src = (uint32_t *)binaries[binary].start; for (i = 0; i < (size / 4); i++) { dst[i] = src[i]; DCCMVAU(&dst[i]); } mark_alloc(p->vmem_allocator, 0x40000000, size); umem_map_pages(p, 0x40000000, kvtop(p->image), size, UMEM_RW); /* * Set up some process variables */ memset(&p->context, 0, sizeof(struct ctx)); p->context.spsr = ARM_MODE_USER; p->context.ret = 0x40000000; /* jump to process img */ p->id = pid++; p->size = size; list_insert(&process_list, &p->list); p->flags.pr_ready = 1; p->flags.pr_kernel = 0; INIT_LIST_HEAD(p->sockets); p->max_fildes = 0; wait_list_init(&p->endlist); return p; } /** * Create a kernel thread! This thread cannot be started with start_process(), * but may be context-switched in. */ struct process *create_kthread(void (*func)(void *), void *arg) { struct process *p = slab_alloc(proc_slab); p->id = pid++; p->size = 0; p->flags.pr_ready = 1; p->flags.pr_kernel = 1; p->kstack = (void *)kmem_get_pages(4096, 0) + 4096; /* kthread is in kernel memory space, no user memory region */ p->vmem_allocator = NULL; p->ttbr0 = 0; p->first = NULL; p->shadow = NULL; INIT_LIST_HEAD(p->sockets); p->max_fildes = 0; memset(&p->context, 0, sizeof(struct ctx)); p->context.spsr = (uint32_t)ARM_MODE_SYS; p->context.a1 = (uint32_t)arg; p->context.ret = (uint32_t)func; p->context.sp = (uint32_t)(p->kstack); wait_list_init(&p->endlist); return p; } void destroy_current_process() { struct socket *sock; // printf("[kernel]\t\tdestroy process %u (p=0x%x)\n", proc->id, proc); preempt_disable(); /* * Remove from the global process list */ list_remove(&current->list); if (!current->flags.pr_kernel) { /* * Free the process image's physical memory (it's not mapped * anywhere except for the process's virtual address space) */ kmem_free_pages(current->image, current->size); /* * Free the process's virtual memory allocator. */ kmem_free_pages(current->vmem_allocator, 0x1000); /* * Find any second-level page tables, and free them too! */ umem_cleanup(current); /* * Free the first-level table + shadow table */ kmem_free_pages(current->first, 0x4000); } else { } list_for_each_entry(sock, &current->sockets, sockets) { socket_destroy(sock); } wait_list_awaken(&current->endlist); wait_list_destroy(&current->endlist); /* * Free the kernel stack, which we stored the other end of for * our full-descending implementation. * * This is tricky because we're currently using that stack! This here is * a bit of a fudge, but we can simply reset the stack pointer to the * initial kernel stack to enable our final call into schedule. */ asm volatile("ldr sp, =stack_end" :::); kmem_free_pages((void *)current->kstack - 4096, 4096); slab_free(proc_slab, current); /* * Mark current as null for schedule(), to inform it that we can't * continue running this process even if there are no other options. * * However first we must disable preemption (which will get re-enabled * once the context switch is complete). This is because if we * rescheduled after setting current to NULL, then we would attempt to * store context into a null pointer. If you don't believe it, feel free * to uncomment the WFI instruction and play around. */ current = NULL; /*asm("wfi");*/ schedule(); } void __nopreempt context_switch(struct process *new_process) { if (new_process == current) { preempt_enable(); return; } /* current could be NULL in two cases: * 1. Starting the first process after initialization. * 2. After destroying a process. * In either case, we don't care to store the context, so don't. */ if (current) if (setctx(&current->context)) return; /* This is where we get scheduled back in */ /* Set the current ASID */ set_cpreg(new_process->id, c13, 0, c0, 1); /* Set ttbr */ set_ttbr0(new_process->ttbr0); current = new_process; /* TODO: It is possible for ASIDs to overlap. Need to check for this and * invalidate caches. */ /* TODO: Speculative execution could result in weirdness when ASID is * changed and TTBR is changed (non-atomically). See B3.10.4 in ARMv7a * reference for solution. */ cxtk_track_proc(); preempt_enable(); resctx(0, &current->context); } struct process *choose_new_process(void) { struct process *iter, *chosen = NULL; int count_seen = 0, count_ready = 0; list_for_each_entry(iter, &process_list, list) { count_seen++; if (iter->flags.pr_ready) { count_ready++; if (iter != current) { chosen = iter; break; } } } if (chosen) { /* * A new process is chosen, move it to the end to give other * processes a chance (round robin scheduler). */ list_remove(&chosen->list); list_insert_end(&process_list, &chosen->list); return chosen; } else if (current && current->flags.pr_ready) { /* * There are no other options, but the current process still * exists and is still runnable. Just keep running it. */ return current; } else { /* * At this point, either there is no process available at all, * or no process is ready. We'll use the IDLE process, which is * always marked as not ready, but in reality we can always * idle a bit. */ static bool warned = false; if (count_seen == 0 && !warned) { puts("[kernel] WARNING: no more processes remain, " "dropping into kernel shell\n"); warned = true; chosen = create_kthread(ksh, KSH_BLOCK); list_insert(&process_list, &chosen->list); return chosen; } return idle_process; } } void irq_schedule(struct ctx *ctx) { struct process *new = choose_new_process(); if (current == new) return; /* Set the current ASID */ set_cpreg(new->id, c13, 0, c0, 1); /* Set ttbr */ set_ttbr0(new->ttbr0); /* Swap contexts! */ current->context = *ctx; current = new; *ctx = current->context; cxtk_track_proc(); /* returning from IRQ is mandatory, swapping ctx will cause us to return * to the new context */ } /** * Choose and context switch into a different active process. */ void __nopreempt schedule(void) { struct process *proc; preempt_disable(); cxtk_track_schedule(); proc = choose_new_process(); context_switch(proc); } int32_t process_image_lookup(char *name) { int32_t i; for (i = 0; i < nelem(binaries); i++) if (strcmp(binaries[i].name, name) == 0) return i; return -1; } static int cmd_mkproc(int argc, char **argv) { struct process *newproc; int img; if (argc != 1) { puts("usage: proc create BINNAME"); return 1; } img = process_image_lookup(argv[0]); if (img == -1) { printf("unknown binary \"%s\"\n", argv[0]); return 2; } newproc = create_process(img); printf("created process with pid=%u\n", newproc->id); return 0; } static int cmd_lsproc(int argc, char **argv) { struct process *p; list_for_each_entry(p, &process_list, list) { printf("%u\n", p->id); } return 0; } static int cmd_execproc(int argc, char **argv) { unsigned int pid; struct process *p; if (argc != 1) { puts("usage: proc exec PID\n"); return 1; } pid = atoi(argv[0]); printf("starting process execution with pid=%u\n", pid); list_for_each_entry(p, &process_list, list) { if (p->id == pid) { break; } } if (p->id != pid) { printf("pid %u not found\n", pid); return 2; } context_switch(p); return 0; } struct ksh_cmd proc_ksh_cmds[] = { KSH_CMD("create", cmd_mkproc, "create new process given binary image"), KSH_CMD("ls", cmd_lsproc, "list process IDs"), KSH_CMD("exec", cmd_execproc, "run process"), { 0 }, }; static void idle(void *arg) { while (1) { uint32_t cpsr; if (!interrupts_enabled()) puts("ERROR: idling with interrupts disabled\n"); cpsr = get_cpsr(); if ((cpsr & ARM_MODE_MASK) != ARM_MODE_SYS) printf("ERROR: idling in non-sys mode. CPSR=0x%x\n", cpsr); asm("wfi"); } } /* * Initialization for processes. */ void process_init(void) { INIT_LIST_HEAD(process_list); proc_slab = slab_new("process", sizeof(struct process), kmem_get_page); idle_process = create_kthread(idle, NULL); idle_process->flags.pr_ready = 0; /* idle process is never ready */ }
C
#include<stdio.h> int main() { int a,b,c; printf("enter the number of rows:"); scanf("%d",&c); for(a=0;a<c;a++) { for(b=0;b<c;b++) { if(a==b||a+b==(c-1)) { printf("*"); } else { printf(" "); } } printf("\n"); } }
C
/** * * Return an array of size *returnSize. * * Note: The returned array must be malloced, assume caller calls free(). * */ int* singleNumber(int* nums, int numsSize, int* returnSize) { int n = nums[0]; for(int i = 1; i < numsSize; i ++){ n = n^nums[i]; } int d[32]; int j = 0; for (int i = 0; i < 32; i++) { // assuming a 32 bit int d[i] = n & (1 << i) ? 1 : 0; } while(j < 32){ if(d[j] == 1) break; j ++; } int base = 1; for(int k = 0; k < j; k ++){ base *= 2; } *returnSize = 2; int *re = malloc(sizeof(int) * 2); re[0] = 0; re[1] = 0; int temp = 0; for(int i = 0; i < numsSize; i ++){ temp = nums[i]&base; if(temp == base){ re[0] = re[0]^nums[i]; } else{ re[1] = re[1]^nums[i]; } } return re; }
C
//#include <stdio.h> //#include <stdlib.h> // //#include <fcntl.h> //#include <unistd.h> // //#include <string.h> //#include <stdbool.h> // //#include <time.h> // // ////set //#define bufferSize 256 //#define blockSize 256 // // ////make sth //// //int createLinuxFile(char *fileName); //int openLinuxFile(char* fileName); //int writeBlockOnLinuxFile(char* fileName, int blockNumber, char* buffer); //int readBlockOnLinuxFile(char* fileName, int blockNumber, char* buffer); #include "linux_file_test.h" /* * 파일 생성이 성공하면 파일 디스크립터를 반환한다. * * 유저명은 유니크하다. * 유저별로 유니크한 디렉토리를 가진다. * 파일은 유저별로 유니크하게 가진다. * 파일은 디렉토리에 속한다. * * */ int createLinuxFile(char *fileName){ int fd = -1; //파일 디스크립터 얻기 fd = open(fileName, O_CREAT | O_RDWR | O_APPEND , 0644); if( fd < 0){ printf("file create error\n"); return fd; } close(fd); //생성되었다는 것만 체크 return fd; } int openLinuxFile(char* fileName){ int fd; fd = open(fileName, O_RDWR); if( fd < 0){ printf("file open error\n"); return fd; } return fd; } // //bool checkAvailableBlockOnLinuxFile(char* fileName){ // // // // return true; //} int writeBlockOnLinuxFile(char* fileName, int blockNumber, char* buffer){ int writeAmount=0; int fd; fd = openLinuxFile(fileName); if(fd <= 0 ){ return -1; } printf("##fileName : %s\n", fileName); lseek(fd, blockNumber * blockSize ,SEEK_SET); writeAmount = write(fd, buffer, bufferSize-1); if( writeAmount < 0 ){ printf("write error \n"); return writeAmount; } if( fsync(fd) == -1){ printf("fsync error\n"); } printf("write amount : %d\n", writeAmount); close(fd); return writeAmount; } //block 구분을 위해서는 시작의 offset 값이 필요하겠습니다. int readBlockOnLinuxFile(char* fileName, int blockNumber, char* buffer){ int readAmount=1; int totalReadAmount=0; int fd; // char buffer[bufferSize]; fd = openLinuxFile(fileName); if(fd <= 0 ){ return -1; } //bufferSize == blockSize lseek(fd, blockSize * blockNumber, SEEK_SET); memset(buffer, 0, bufferSize); readAmount = read(fd, buffer, bufferSize); printf("%s\n",buffer); if(readAmount < 0){ printf("read error\n"); return -1; } close(fd); totalReadAmount += readAmount; return totalReadAmount; } int printBlock(char* fileName, int blockNumber){ int fd; fd = openLinuxFile(fileName); if( fd < 0 ){ return -1; } return 1; } //어차피 블록단위로 파일 사이즈가 결정될텐데 카운트할 필요가 있나? 싶다. int countBlockSizeOnLinuxFile(char* fileName, int blockNumber){ return -1; } /* * Linux File * 1) create * 2) read * 3) write * * * */ //int main(){ // // char *fileName = "test1.txt"; // char buffer[bufferSize]; // // int thisFd; // int writeAmount; // int readAmount; // // memset(buffer,0,bufferSize); // sprintf(buffer, "%s","Hello new World"); //// printf("%s\n",buffer); // // thisFd = createLinuxFile(fileName); // printf("fd -> %d\n", thisFd); // // // writeAmount = writeBlockOnLinuxFile(fileName, 1, buffer); // printf("write -> %d\n", writeAmount); // // // memset(buffer, 0, bufferSize); // readAmount = readBlockOnLinuxFile(fileName, 1, buffer); // printf("read -> %d\n",readAmount); // printf("readAmount -> %d\n",readAmount); // printf("%s\n", buffer); // // // close(thisFd); // return 0; //}
C
#include <math.h> #define LAG_COMPARISON_ENABLED extern double * baseline; double max_xcorr(double *signal, double *template, int bins); double normalized_xcorr(double *signal, double *template, int bins, int lag); double avg(double *data, int length); double std_dev(double *data, int length, double avg); int match( double *test, double *reference, int bins, double threshold ) { // first test against the baseline for quick failures double baseline_xcorr = max_xcorr(test, baseline, bins); if (baseline_xcorr > threshold) { // it's a pure background signal, not fissile material here return 0; } // it's not a background signal, time to test against a reference model double reference_xcorr = max_xcorr(test, reference, bins); if (reference_xcorr < threshold) { // it does not match the reference, not fissile material here return 0; } else { return 1; } } /** * Determines the maximum normalized cross correlation between two spectra for a series of * offesets up to half the length of the arrays. The choice of N/2 is somewhat arbitrary but * inspired by Nyquist */ double max_xcorr(double *signal, double *template, int bins) { // test zero shift first double max = normalized_xcorr(signal, template, bins, 0); // this feature seems contentious, hide behind a flag so easily disabled. #ifdef LAG_COMPARISON_ENABLED // only allow to shift half the signal away for (int i=1; i<bins/2; i++) { double xcorr = normalized_xcorr(signal, template, bins, i); if (xcorr > max) { max = xcorr; } } #endif return max; } /** * Calcluates the normalized cross correlation between two spectra, returns a double * valoue between -1 and 1, 0 indicating no corrleation, 1 perfect correlation and -1 * perfect negative correlation. See: * https://en.wikipedia.org/wiki/Cross-correlation#Normalized_cross-correlation * * Note: lag is experimental, please feel free to turn on/off as desired */ double normalized_xcorr(double *signal, double *template, int bins, int lag) { bins -= lag; // lag fewer bins signal += lag; // advance the signal pointer lag bins double signal_avg = avg(signal, bins); double template_avg = avg(template, bins); double signal_std_dev = std_dev(signal, bins, signal_avg); double template_std_dev = std_dev(template, bins, template_avg); double xcorr = 0.0; for (int i=0; i<bins; i++) { xcorr += (signal[i] - signal_avg)*(template[i] - template_avg) / (signal_std_dev*template_std_dev); } xcorr = xcorr/bins; return xcorr; } /** * Computes the average of an array of doubles * https://en.wikipedia.org/wiki/Average#Arithmetic_mean */ double avg(double *data, int length) { double average = 0.0; for (int i=0; i<length; i++) { average += data[i]; } average = average/length; return average; } /** * Computes the standard deviation of an array of doubles given that the average has already * been computed https://en.wikipedia.org/wiki/Standard_deviation#Discrete_random_variable */ double std_dev(double *data, int length, double avg) { double inner_sum = 0.0; for (int i=0; i<length; i++) { inner_sum += (data[i] - avg)*(data[i] - avg); } return sqrt(inner_sum/length); }