language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * Copyright (C) Niklaus F.Schen. */ #include "mln_array.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static inline int mln_array_alloc(mln_array_t *arr, mln_size_t n); int mln_array_init(mln_array_t *arr, struct mln_array_attr *attr) { arr->elts = NULL; arr->size = attr->size; arr->nalloc = attr->nalloc; arr->nelts = 0; arr->pool = attr->pool; arr->pool_alloc = attr->pool_alloc; arr->pool_free = attr->pool_free; arr->free = attr->free; return mln_array_alloc(arr, arr->nalloc); } mln_array_t *mln_array_new(struct mln_array_attr *attr) { mln_array_t *arr; if (attr->pool == NULL || attr->pool_alloc == NULL || attr->pool_free == NULL) { arr = (mln_array_t *)malloc(sizeof(mln_array_t)); attr->pool = NULL; } else { arr = (mln_array_t *)attr->pool_alloc(attr->pool, sizeof(mln_array_t)); } if (mln_array_init(arr, attr) < 0) { if (attr->pool == NULL || attr->pool_alloc == NULL || attr->pool_free == NULL) free(arr); else attr->pool_free(arr); return NULL; } return arr; } void mln_array_destroy(mln_array_t *arr) { if (arr == NULL) return; if (arr->free != NULL && arr->nelts) { mln_u8ptr_t p = arr->elts, pend = arr->elts + (arr->nelts * arr->size); for (; p < pend; p += arr->size) arr->free(p); } if (arr->pool != NULL) arr->pool_free(arr->elts); else free(arr->elts); } void mln_array_free(mln_array_t *arr) { if (arr == NULL) return; if (arr->free != NULL && arr->nelts) { mln_u8ptr_t p = arr->elts, pend = arr->elts + (arr->nelts * arr->size); for (; p < pend; p += arr->size) arr->free(p); } if (arr->pool != NULL) { arr->pool_free(arr->elts); arr->pool_free(arr); } else { free(arr->elts); free(arr); } } void mln_array_reset(mln_array_t *arr) { if (arr == NULL) return; if (arr->free != NULL && arr->nelts) { mln_u8ptr_t p = arr->elts, pend = arr->elts + (arr->nelts * arr->size); for (; p < pend; p += arr->size) arr->free(p); } arr->nelts = 0; } void *mln_array_push(mln_array_t *arr) { if (arr->nelts >= arr->nalloc) { if (mln_array_alloc(arr, 1) < 0) return NULL; } return arr->elts + (arr->nelts++) * arr->size; } void *mln_array_pushn(mln_array_t *arr, mln_size_t n) { mln_u8ptr_t ptr; if (arr->nelts + n > arr->nalloc) { if (mln_array_alloc(arr, n) < 0) return NULL; } ptr = arr->elts + arr->nelts * arr->size; arr->nelts += n; return ptr; } static inline int mln_array_alloc(mln_array_t *arr, mln_size_t n) { mln_u8ptr_t ptr; mln_size_t num = arr->nalloc; while (n + arr->nelts > num) { num <<= 1; } if (arr->pool != NULL) { ptr = arr->pool_alloc(arr->pool, num * arr->size); } else { ptr = malloc(num * arr->size); } if (ptr == NULL) return -1; memcpy(ptr, arr->elts, arr->nelts * arr->size); if (arr->pool != NULL) arr->pool_free(arr->elts); else free(arr->elts); arr->elts = ptr; arr->nalloc = num; return 0; } void mln_array_pop(mln_array_t *arr) { if (arr == NULL || !arr->nelts) return; if (arr->free != NULL) arr->free(arr->elts + (arr->nelts - 1) * arr->size); --arr->nelts; }
C
/* * icmp.c - support for Internet Control Message Protocol (ICMP) */ #include <string.h> #include <asm/chksum.h> #include <base/compiler.h> #include <base/log.h> #include <net/icmp.h> #include <net/ping.h> #include "defs.h" static void net_rx_icmp_echo(struct mbuf *m_in, const struct icmp_pkt *in_icmp_pkt, const struct ip_hdr *in_iphdr, uint16_t len) { struct mbuf *m; struct icmp_hdr *out_icmp_hdr; log_debug("icmp: responding to icmp echo request"); m = net_tx_alloc_mbuf(); if (unlikely(!m)) { mbuf_drop(m_in); return; } /* copy incoming ICMP hdr and data, set type and checksum */ out_icmp_hdr = (struct icmp_hdr *)mbuf_put(m, len); memcpy(out_icmp_hdr, in_icmp_pkt, len); out_icmp_hdr->type = ICMP_ECHOREPLY; out_icmp_hdr->chksum = 0; out_icmp_hdr->chksum = chksum_internet((char *)out_icmp_hdr, len); /* send the echo reply */ net_tx_ip_or_free(m, IPPROTO_ICMP, ntoh32(in_iphdr->saddr)); mbuf_free(m_in); } static void net_rx_icmp_echo_reply(struct mbuf *m, const struct icmp_pkt *icmp_pkt, uint16_t len) { struct ping_payload *payload; log_debug("icmp: received icmp echo reply"); payload = mbuf_pull_hdr_or_null(m, *payload); if (unlikely(!payload)) goto drop; net_recv_ping(payload, icmp_pkt); drop: mbuf_free(m); } void net_rx_icmp(struct mbuf *m, const struct ip_hdr *iphdr, uint16_t len) { struct icmp_pkt *icmp_pkt; icmp_pkt = (struct icmp_pkt *)mbuf_pull_or_null(m, ICMP_MINLEN); if (unlikely(!icmp_pkt)) goto drop; switch (icmp_pkt->hdr.type) { case ICMP_ECHO: net_rx_icmp_echo(m, icmp_pkt, iphdr, len); break; case ICMP_ECHOREPLY: net_rx_icmp_echo_reply(m, icmp_pkt, len); break; default: log_err("icmp: type %d not yet supported", icmp_pkt->hdr.type); goto drop; } return; drop: mbuf_drop(m); } int net_tx_icmp(struct mbuf *m, uint8_t type, uint8_t code, uint32_t daddr, uint16_t id, uint16_t seq) { struct icmp_pkt *icmp_pkt; log_debug("icmp: sending icmp with type %u, code %u", type, code); /* populate ICMP header */ icmp_pkt = (struct icmp_pkt *)mbuf_push(m, ICMP_MINLEN); icmp_pkt->hdr.type = ICMP_ECHO; icmp_pkt->hdr.code = 0; icmp_pkt->icmp_id = id; icmp_pkt->icmp_seq = seq; icmp_pkt->hdr.chksum = 0; icmp_pkt->hdr.chksum = chksum_internet((char *)icmp_pkt, mbuf_length(m)); return net_tx_ip(m, IPPROTO_ICMP, daddr); }
C
/****************************************************************** * * Round for C * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #if !defined(WIN32) #include <signal.h> #endif #include <string.h> #include <round/util/thread.h> #include <round/util/timer.h> static void round_sig_handler(int sign); /**************************************** * Thread Function ****************************************/ static int RoundExecThreadAction(RoundThread* thread) { if (!thread->action) return 0; if (round_thread_isstarttimeenabled(thread)) { double sleepTime = round_thread_getstarttime(thread) - round_getcurrentunixtime(); round_sleep(sleepTime); } double actionStartTime, actionExecTime; actionStartTime = round_getcurrentunixtime(); thread->action(thread); actionExecTime = round_getcurrentunixtime() - actionStartTime; while (round_thread_isloop(thread) && round_thread_isrunnable(thread)) { if (round_thread_isstoptimeenabled(thread)) { if (round_thread_getstoptime(thread) < round_getcurrentunixtime()) break; } round_sleep(round_thread_getcycleinterval(thread) - actionExecTime); actionStartTime = round_getcurrentunixtime(); thread->action(thread); actionExecTime = round_getcurrentunixtime() - actionStartTime; } return 0; } #if defined(WIN32) static DWORD WINAPI RoundWin32ThreadProc(LPVOID lpParam) { RoundThread* thread = (RoundThread*)lpParam; thread->runningFlag = true; RoundExecThreadAction(thread); thread->runningFlag = false; return 0; } #else static void* RoundPosixThreadProc(void* param) { sigset_t set; struct sigaction actions; RoundThread* thread = (RoundThread*)param; sigfillset(&set); sigdelset(&set, SIGQUIT); pthread_sigmask(SIG_SETMASK, &set, NULL); memset(&actions, 0, sizeof(actions)); sigemptyset(&actions.sa_mask); actions.sa_flags = 0; actions.sa_handler = round_sig_handler; sigaction(SIGQUIT, &actions, NULL); RoundExecThreadAction(thread); thread->runningFlag = false; return 0; } #endif /**************************************** * round_thread_init ****************************************/ bool round_thread_init(RoundThread* thread) { round_list_node_init((RoundList*)thread); thread->runnableFlag = false; thread->action = NULL; thread->userData = NULL; round_thread_setloop(thread, false); round_thread_setcycleinterval(thread, 0.0); round_thread_setstarttime(thread, 0.0); round_thread_setstoptime(thread, 0.0); thread->name = round_string_new(); if (!thread->name) return false; return true; } /**************************************** * round_thread_new ****************************************/ RoundThread* round_thread_new(void) { RoundThread* thread; thread = (RoundThread*)malloc(sizeof(RoundThread)); if (!thread) return NULL; if (!round_thread_init(thread)) { round_thread_delete(thread); return NULL; } return thread; } /**************************************** * round_thread_delete ****************************************/ bool round_thread_delete(RoundThread* thread) { if (!thread) return false; if (thread->runnableFlag) { round_thread_stop(thread); } round_thread_remove(thread); free(thread); return true; } /**************************************** * round_thread_start ****************************************/ bool round_thread_start(RoundThread* thread) { if (!thread) return false; thread->runnableFlag = true; thread->runningFlag = true; #if defined(WIN32) thread->hThread = CreateThread(NULL, 0, RoundWin32ThreadProc, (LPVOID)thread, 0, &thread->threadID); #else pthread_attr_t thread_attr; if (pthread_attr_init(&thread_attr) != 0) { thread->runnableFlag = false; return false; } if (pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED) != 0) { thread->runnableFlag = false; pthread_attr_destroy(&thread_attr); return false; } if (pthread_create(&thread->pThread, &thread_attr, RoundPosixThreadProc, thread) != 0) { thread->runnableFlag = false; pthread_attr_destroy(&thread_attr); return false; } pthread_attr_destroy(&thread_attr); #endif return true; } /**************************************** * round_thread_stop ****************************************/ bool round_thread_stop(RoundThread* thread) { if (!thread) return false; if (thread->runningFlag) { thread->runnableFlag = false; #if defined(WIN32) TerminateThread(thread->hThread, 0); WaitForSingleObject(thread->hThread, INFINITE); #else pthread_kill(thread->pThread, 0); /* TODO : Fix to use pthread_join */ /* Now we wait one second for thread termination instead of using pthread_join */ round_sleep(ROUND_THREAD_MIN_SLEEP); #endif } thread->runnableFlag = false; thread->runningFlag = false; return true; } /**************************************** * round_thread_restart ****************************************/ bool round_thread_restart(RoundThread* thread) { round_thread_stop(thread); return round_thread_start(thread); } /**************************************** * round_thread_isrunnable ****************************************/ bool round_thread_isrunnable(RoundThread* thread) { if (!thread) return false; #if !defined(WIN32) pthread_testcancel(); #endif return thread->runnableFlag; } /**************************************** * round_thread_isrunning ****************************************/ bool round_thread_isrunning(RoundThread* thread) { if (!thread) return false; return thread->runningFlag; } /**************************************** * round_thread_setaction ****************************************/ void round_thread_setaction(RoundThread* thread, RoundThreadFunc func) { if (!thread) return; thread->action = func; } /**************************************** * round_thread_setuserdata ****************************************/ void round_thread_setuserdata(RoundThread* thread, void* value) { if (!thread) return; thread->userData = value; } /**************************************** * round_thread_getuserdata ****************************************/ void* round_thread_getuserdata(RoundThread* thread) { if (!thread) return NULL; return thread->userData; } /**************************************** * round_sig_handler ****************************************/ static void round_sig_handler(int sign) {}
C
#include <stdio.h> #include <stdlib.h> void funcao_maior_parametro(int *a,int *b, int *c) //referencia dos parametros das variaveis(valor1,valor2,valor3) { if(*a > *b && *a > *c && *b > *c) //pega as variaveis ponteiros , e compara com os valores digitados { printf("%d e maior que %d que maior que %d",*a,*b,*c); //asterisco mostra os valores dos ponteiros } else if(*a > *b && *a > *c && *c > *b) { printf("%d e maior que %d que maior que %d",*a,*c,*b);//asterisco mostra os valores onde apontam os ponteiros } else if(*b > *a && *b > *c && *a > *c) { printf("%d e maior que %d que maior que %d",*b,*a,*c);//asterisco mostra os valores onde apontam os ponteiros } else if(*b > *a && *b > *c && *c > *a) { printf("%d e maior que %d que maior que %d",*b,*c,*a);//asterisco mostra os valores onde apontam os ponteiros } else if(*c > *a && *c > *b && *a > *b) { printf("%d e maior que %d que maior que %d",*c,*a,*b);//asterisco mostra os valores onde apontam os ponteiros } else if(*c > *a && *c > *b && *b > *a) { printf("%d e maior que %d que maior que %d",*c,*b,*a);//asterisco mostra os valores onde apontam os ponteiros } } int main() { int valor1,valor2,valor3; printf("Digite 3 valores separados por espao \n"); scanf("%d %d %d", &valor1, &valor2, &valor3); funcao_maior_parametro(&valor1,&valor2,&valor3);//com o &(e-comercial) e passado por /*parametro*/ }
C
#include <stdio.h> int main() { int x, y, i = 10; for (x = 1; x <= 5; x++) { for(y = 1; y <= 6; y++) printf(" %d ", x); printf("\n"); } printf("\n"); for (x = 1; x <= 5; x++) { for(y = 1; y <= 6; y++) printf(" %d ", y); printf("\n"); } printf("\n"); for (x = 1; x <= 5; x++) { for(y = 1; y <= 3; y++) { printf(" %d ", i); i += 5; // value of x accumulated by 5 } printf("\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* spawn.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: home <home@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/12 17:53:28 by home #+# #+# */ /* Updated: 2020/11/30 21:37:29 by home ### ########.fr */ /* */ /* ************************************************************************** */ /* * USAGE:go into the year you are working at and run the compiled file as * `./a.out YEAR DAY` where YEAR is a number between 2015 and 2019 and * DAY is a number between 1 or 25. */ #include <stdio.h> // asprintf #include <assert.h> //assert #include <stdlib.h> //aoti #include <sys/stat.h> //mkdir #include <unistd.h> //chdir #include <fcntl.h> //open void make_day(char *s_year, char *s_day) { int day; int year; char *day_dir; day = atoi(s_day); year = atoi(s_year); printf("%d and %d", year, day); assert(0 < day && day <= 25 && "Day argument is out of bounds. Valid range is [1, 25]."); assert(2015 < year && year <= 2022 && "Year argument is out of bounds. Valid range is [2015, 2022]"); asprintf(&day_dir, "day_%02d", day); mkdir(day_dir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); chdir(day_dir); int fd; char *p1_str; char *p2_str; asprintf(&p1_str, "p_%d_%02d_01.c", year, day); asprintf(&p2_str, "p_%d_%02d_02.c", year, day); fd = open(p1_str, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); close(fd); fd = open(p2_str, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); close(fd); char *curl_cmd; /* NOTE: requires a file called aoc_cookies.txt that has your aoc account information */ asprintf(&curl_cmd, "curl --cookie ~/aoc_cookies.txt -o input.txt \"https://adventofcode.com/%d/day/%d/input\"", year, day); system(curl_cmd); } int main(int aa, char **args) { assert(aa == 3 && "Insufficient Arguments provided. Please supply a Year and a Day."); make_day(args[1], args[2]); return (0); }
C
#include<stdio.h> int temp(); int main(){ temp(); } int temp(){ float temp[6], sum=0.0, average; for(int x=1;x<=7;x++){ printf("Enter temperature of day %d: ",x); scanf("%f",&temp[x]); sum+=temp[x]; } average=sum/7; printf("\nAverage weather for seven day will be: %f",average); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_6__ TYPE_1__ ; /* Type definitions */ typedef TYPE_1__* db_watchpoint_t ; struct TYPE_6__ {struct TYPE_6__* link; } ; /* Variables and functions */ size_t NWATCHPOINTS ; TYPE_1__* db_free_watchpoints ; TYPE_1__* db_next_free_watchpoint ; int /*<<< orphan*/ db_printf (char*) ; TYPE_1__* db_watch_table ; __attribute__((used)) static db_watchpoint_t db_watchpoint_alloc(void) { db_watchpoint_t watch; if ((watch = db_free_watchpoints) != 0) { db_free_watchpoints = watch->link; return (watch); } if (db_next_free_watchpoint == &db_watch_table[NWATCHPOINTS]) { db_printf("All watchpoints used.\n"); return (0); } watch = db_next_free_watchpoint; db_next_free_watchpoint++; return (watch); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstnew.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jrivas-z <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/20 19:15:24 by jrivas-z #+# #+# */ /* Updated: 2020/01/27 18:52:44 by jrivas-z ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static void ft_copy_arrays(char *dst, char *src) { int size; size = 0; while (src[size]) { dst[size] = src[size]; size++; } dst[size] = '\0'; } t_list *ft_lstnew(void *content) { t_list *list; size_t size; char *dst; char *src; if (!(list = (t_list *)malloc(sizeof(*list)))) return (NULL); if (!content) list->content = NULL; else { src = (char *)content; size = ft_strlen(src); if (!(list->content = (void *)malloc(size + 1))) { free(list); return (NULL); } dst = (char *)(list->content); ft_copy_arrays(dst, src); } list->next = NULL; return (list); }
C
#include "ADC_Config.h" /******************************************************************************************** Name: ADC_Init. Purpose: Initialize, all possible ADC registers for ATmega32 and Enables it. Entry: (Struct_ADC) a STRUCT that setup the following. 1) Voltage reference. 2) Result Adjustment in ADCL and ADCH registers. 3) Prescaler, The ADC operates at freq from 50kHz ~ 250kHz. 4) Trigger settings if it is needed. 5) Adjustment of the trigger source. 6) Interrupt, if needed. Exit: no parameters ********************************************************************************************/ void ADC_Init ( Struct_ADC ADC_Config){ ADCSRA |= (1 << ADEN); /* Enable the ADC */ switch(ADC_Config.Vref_Reference_Select){ case Vref_Internal_Vref_OFF : ADMUX &=~(1 << REFS1); ADMUX &=~(1 << REFS0); break; case Vref_VCC_With_ext_cap : ADMUX &=~(1 << REFS1); ADMUX |= (1 << REFS0); break; case Vref_2_56_Volt : ADMUX |= (1 << REFS1); ADMUX |= (1 << REFS0); break; default : ADMUX &=~(1 << REFS1); ADMUX &=~(1 << REFS0); break; } switch(ADC_Config.Result_Adjustmment){ case Left_Adjustment : ADMUX |= (1 << ADLAR); break; case Right_Adjustment : ADMUX &=~(1 << ADLAR); break; default : ADMUX &=~(1 << ADLAR); break; } switch(ADC_Config.Prescaler_Select){ case Division_Factor_2 : ADCSRA &=~ (1 << ADPS2); ADCSRA &=~ (1 << ADPS1); ADCSRA |= (1 << ADPS0); break; case Division_Factor_4 : ADCSRA &=~ (1 << ADPS2); ADCSRA |= (1 << ADPS1); ADCSRA &=~ (1 << ADPS0); break; case Division_Factor_8 : ADCSRA &=~ (1 << ADPS2); ADCSRA |= (1 << ADPS1); ADCSRA |= (1 << ADPS0); break; case Division_Factor_16 : ADCSRA |= (1 << ADPS2); ADCSRA &=~ (1 << ADPS1); ADCSRA &=~ (1 << ADPS0); break; case Division_Factor_32 : ADCSRA |= (1 << ADPS2); ADCSRA &=~ (1 << ADPS1); ADCSRA |= (1 << ADPS0); break; case Division_Factor_64 : ADCSRA |= (1 << ADPS2); ADCSRA |= (1 << ADPS1); ADCSRA &=~ (1 << ADPS0); break; case Division_Factor_128 : ADCSRA |= (1 << ADPS2); ADCSRA |= (1 << ADPS1); ADCSRA |= (1 << ADPS0); break; default : ADCSRA &=~ (1 << ADPS2); ADCSRA &=~ (1 << ADPS1); ADCSRA &=~ (1 << ADPS0); break; } switch(ADC_Config.Trigger_Select){ case AutoTrigger_Enable : ADCSRA |= (1 << ADATE); break; case AutoTrigger_Disable : ADCSRA &=~(1 << ADATE); break; default : ADCSRA &=~(1 << ADATE); break; } switch(ADC_Config.Trigger_Src_Select){ case Free_Running_Mode : SFIOR &=~(1 << ADTS2); SFIOR &=~(1 << ADTS1); SFIOR &=~(1 << ADTS0); break; case Analog_Comparator : SFIOR &=~(1 << ADTS2); SFIOR &=~(1 << ADTS1); SFIOR |= (1 << ADTS0); break; case Ext_Interrupt_Req0 : SFIOR &=~(1 << ADTS2); SFIOR |= (1 << ADTS1); SFIOR &=~(1 << ADTS0); break; case Timer0_CMP_Match : SFIOR &=~(1 << ADTS2); SFIOR |= (1 << ADTS1); SFIOR |= (1 << ADTS0); break; case Timer0_Overflow : SFIOR |= (1 << ADTS2); SFIOR &=~(1 << ADTS1); SFIOR &=~(1 << ADTS0); break; case Timer1_CMP_MatchB : SFIOR |= (1 << ADTS2); SFIOR &=~(1 << ADTS1); SFIOR |= (1 << ADTS0); break; case Timer1_Overflow : SFIOR |= (1 << ADTS2); SFIOR |= (1 << ADTS1); SFIOR &=~(1 << ADTS0); break; case Timer1_Capture_Event : SFIOR |= (1 << ADTS2); SFIOR |= (1 << ADTS1); SFIOR |= (1 << ADTS0); break; default : SFIOR &=~(1 << ADTS2); SFIOR &=~(1 << ADTS1); SFIOR &=~(1 << ADTS0); break; } switch(ADC_Config.Interrupt_Select){ case Interrupt_Disable : ADCSRA &=~(1 << ADIE); break; case Interrupt_Enable : ADCSRA |= (1 << ADIE); break; default : ADCSRA &=~(1 << ADIE); break; } } /******************************************************************************************** Name: ADC_Scan. Purpose: Setup the ADC channel and starts the conversion. Entry: (Channel_Select) The Channel number that you are gonna work with (0 ~ 7). Exit: (u68 ADC) Returns the value of the ADC conversion of the two registers. ********************************************************************************************/ u16 ADC_Scan ( u8 Channel_Select ){ Channel_Select &= 0x07; ADMUX |= Channel_Select; /* Select ADC Channel */ ADCSRA |= (1 << ADSC); /* Start the Convention */ while (ADCSRA & (1 << ADSC)); /* Wait for the conversion to complete And ADSC bit will Driven LOW */ return ADC; }
C
/* * File: main.c * Author: Raven Minion - Ravenswurk * * Provides the main logic for the Numitron Clock project. Expects to run on a * PIC18F47K40, with I2C to a PCF8583P. * * Created on 20 March 2019, 19:13 */ #include "config.h" #include "i2c1_driver.h" #include <xc.h> #define abs(x) (x<0?-x:x) typedef struct { uint8_t seconds; uint8_t minutes; uint8_t hours; uint8_t mode; uint8_t lastSeconds; } ClockTime_t; uint8_t readRegister(unsigned char readReg) { uint8_t response = 0; i2c1_driver_start(); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_TXData(0xA0); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_TXData(readReg); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_start(); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_TXData(0xA1); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_startRX(); mssp1_waitForEvent(); mssp1_clearIRQ(); response = i2c1_driver_getRXData(); i2c1_driver_sendNACK(); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_stop(); mssp1_waitForEvent(); mssp1_clearIRQ(); return response; } void writeRegister(unsigned char writeReg, unsigned char value) { i2c1_driver_start(); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_TXData(0xA0); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_TXData(writeReg); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_TXData(value); mssp1_waitForEvent(); mssp1_clearIRQ(); i2c1_driver_stop(); mssp1_waitForEvent(); mssp1_clearIRQ(); } void updateTime(ClockTime_t* time) { time->lastSeconds = time->seconds; time->seconds = readRegister(0x02); time->minutes = readRegister(0x03); uint8_t hours = readRegister(0x04); time->mode = (hours & 0x80) >> 7; time->hours = hours & 0x3F; } void updateIndicator(ClockTime_t clockTime) { static uint8_t indicator = 8; if (clockTime.lastSeconds != clockTime.seconds) { indicator = indicator << 1; if (indicator > 8 || indicator == 0) { indicator = 1; } } LATD = indicator; } inline void blinkStatus(uint8_t leftSide, uint8_t rightSide) { for (uint8_t i=0;i<5;i++) { LATC=0xFF; LATA=0xFF; __delay_ms(250); LATC = rightSide; LATA = leftSide; __delay_ms(250); } } void handleBothButtonsPressed(ClockTime_t clockTime, uint16_t runningTime, uint16_t* buttonHoldTime) { if (*buttonHoldTime == -1) { *buttonHoldTime = runningTime; } else if (abs(runningTime - (*buttonHoldTime)) >= 5) { *buttonHoldTime = -1; uint8_t leftSide = 0xFF; uint8_t rightSide = 0xFF; if (clockTime.mode == 0) { if (clockTime.hours > 12) { writeRegister(0x04, (clockTime.hours - 0x12) | 0x80); } rightSide = 0x12; } else { writeRegister(0x04, clockTime.hours & 0x7F); leftSide = 0x24; } blinkStatus(leftSide, rightSide); } } void handleMinuteButton(ClockTime_t clockTime) { clockTime.minutes++; if ((clockTime.minutes & 0x0F) >= 10) { clockTime.minutes += 0x10; clockTime.minutes &= 0xF0; if ((clockTime.minutes & 0xF0) >= 0x60) { clockTime.minutes = 0; } } LATC = clockTime.minutes; writeRegister(0x03, clockTime.minutes); __delay_ms(150); } void handleHourButton(ClockTime_t clockTime) { clockTime.hours++; if ((clockTime.hours & 0x0F) >= 10) { clockTime.hours += 0x10; clockTime.hours &= 0xF0; } if (clockTime.mode == 0 && ((clockTime.hours & 0xF0) >= 0x20) && ((clockTime.hours & 0x0F) >= 0x04)) { clockTime.hours = 0; } else if (clockTime.mode == 1 && ((clockTime.hours & 0xF0) >= 0x10) && ((clockTime.hours & 0x0F) >= 0x03)) { clockTime.hours = 1; } LATA = clockTime.hours; writeRegister(0x04, clockTime.hours | (clockTime.mode << 7)); __delay_ms(150); } void handleButtons(ClockTime_t clockTime) { static uint16_t buttonHoldTime; static uint16_t runningTime; static uint8_t lastTime; // The XC8 compiler doesn't seem to initialise static function variables // correctly and just sets them to 0 regardless of what you ask for. Just // set them here instead. if (buttonHoldTime == 0) { buttonHoldTime = -1; runningTime = 0; lastTime = 0; } if (clockTime.seconds != lastTime) { runningTime++; lastTime = clockTime.seconds; } if (PORTBbits.RB2 && PORTBbits.RB3) { handleBothButtonsPressed(clockTime, runningTime, &buttonHoldTime); } else { buttonHoldTime = -1; if (PORTBbits.RB2) { handleMinuteButton(clockTime); } else if (PORTBbits.RB3) { handleHourButton(clockTime); } } } void main(void) { TRISA = 0; TRISC = 0; TRISD = 0; LATA = 0; LATC = 0; PORTD = 0; ANSELA = 0; ANSELC = 0; ANSELB = 0; PMD3 = 0xFF; PMD4 = 0xEF; SSP1CLKPPS = 0x08; //RB0->MSSP1:SCL1; RB1PPS = 0x10; //RB1->MSSP1:SDA1; RB0PPS = 0x0F; //RB0->MSSP1:SCL1; SSP1DATPPS = 0x09; //RB1->MSSP1:SDA1; i2c1_driver_open(); mssp1_disableIRQ(); ClockTime_t clockTime = {0}; while (1) { updateTime(&clockTime); LATC = clockTime.minutes; LATA = clockTime.hours; updateIndicator(clockTime); handleButtons(clockTime); __delay_ms(50); } }
C
#include "PX_Object.h" PX_Object * PX_ObjectGetChild( PX_Object *Object,px_int Index ) { PX_Object *pObject; if (!Object) { return PX_NULL; } pObject=Object->pChilds; while (Index>0&&pObject) { pObject=pObject->pNextBrother; Index--; } return pObject; } static PX_Object * PX_ObjectGetObjectLink(PX_Object *pObject,const px_char payload[]) { px_char id[PX_OBJECT_ID_MAXLEN]={0}; px_int oft=0; if (!pObject) { return PX_NULL; } while (payload[oft]!='.'&&payload[oft]!='\0'&&oft<PX_OBJECT_ID_MAXLEN-1) { id[oft]=payload[oft]; oft++; } if (payload[oft]=='.') { oft++; } if (payload[oft]=='\0') { if (PX_strequ(pObject->id,id)) { return pObject; } else { return PX_ObjectGetObjectLink(pObject->pNextBrother,payload); } } else { if (PX_strequ(pObject->id,id)) { return PX_ObjectGetObjectLink(pObject->pChilds,payload+oft); } else { return PX_ObjectGetObjectLink(pObject->pNextBrother,payload); } } return PX_NULL; } PX_Object * PX_ObjectGetObject(PX_Object *pObject,const px_char payload[]) { px_char id[PX_OBJECT_ID_MAXLEN]={0}; px_int oft=0; if (!pObject) { return PX_NULL; } while (payload[oft]!='.'&&payload[oft]!='\0'&&oft<PX_OBJECT_ID_MAXLEN-1) { id[oft]=payload[oft]; oft++; } if (payload[oft]=='.') { oft++; } if (payload[oft]=='\0') { if (PX_strequ(pObject->id,id)) { return pObject; } else { return PX_NULL; } } else { if (PX_strequ(pObject->id,id)) { return PX_ObjectGetObjectLink(pObject->pChilds,payload+oft); } } return PX_NULL; } static px_void PX_ObjectSetFocusEx(PX_Object *pObject) { while(pObject) { pObject->OnFocus=PX_TRUE; pObject=pObject->pParent; } } static px_void PX_ObjectClearFocusEx(PX_Object *pObject) { if (!pObject) { return; } pObject->OnFocus=PX_FALSE; pObject->OnFocusNode=PX_FALSE; PX_ObjectClearFocusEx(pObject->pChilds); PX_ObjectClearFocusEx(pObject->pNextBrother); } px_void PX_ObjectClearFocus(PX_Object *pObject) { PX_Object *pClearObject=pObject; if (!pObject->OnFocus) { return; } while(pClearObject->pParent) { pClearObject=pClearObject->pParent; if (pClearObject->OnFocusNode) { pClearObject=pClearObject->pChilds; break; } } PX_ObjectClearFocusEx(pClearObject); } px_void PX_ObjectSetFocus(PX_Object *pObject) { PX_Object *pClearObject=pObject; while(pClearObject->pParent) { pClearObject=pClearObject->pParent; if (pClearObject->OnFocusNode) { pClearObject=pClearObject->pChilds; break; } } PX_ObjectClearFocusEx(pClearObject); pObject->OnFocusNode=PX_TRUE; PX_ObjectSetFocusEx(pObject); } PX_Object * PX_ObjectGetRoot(PX_Object *Object) { while(Object->pParent) { Object=Object->pParent; } return Object; } PX_Object_Event PX_OBJECT_BUILD_EVENT(px_uint Event) { PX_Object_Event e; PX_memset(&e,0,sizeof(e)); e.Event=Event; return e; } PX_Object_Event PX_OBJECT_BUILD_EVENT_STRING(px_uint Event,const px_char *content) { PX_Object_Event e; PX_memset(&e,0,sizeof(e)); e.Event=Event; PX_Object_Event_SetStringPtr(&e,(px_void *)content); return e; } PX_Object_Event PX_OBJECT_BUILD_EVENT_INT(px_uint Event, px_int i) { PX_Object_Event e; PX_memset(&e, 0, sizeof(e)); e.Event = Event; PX_Object_Event_SetIndex(&e, i); return e; } PX_Object_Event PX_Object_Event_CursorOffset(PX_Object_Event e,px_point offset) { switch(e.Event) { case PX_OBJECT_EVENT_CURSORMOVE: case PX_OBJECT_EVENT_CURSORUP: case PX_OBJECT_EVENT_CURSORRDOWN: case PX_OBJECT_EVENT_CURSORDOWN: case PX_OBJECT_EVENT_CURSORRUP: case PX_OBJECT_EVENT_CURSOROVER: case PX_OBJECT_EVENT_CURSOROUT: case PX_OBJECT_EVENT_CURSORWHEEL: case PX_OBJECT_EVENT_CURSORCLICK: case PX_OBJECT_EVENT_CURSORDRAG: PX_Object_Event_SetCursorX(&e,PX_Object_Event_GetCursorX(e)+offset.x); PX_Object_Event_SetCursorY(&e,PX_Object_Event_GetCursorY(e)+offset.y); return e; default: return e; } } px_float PX_Object_Event_GetCursorX(PX_Object_Event e) { return e.Param_float[0]; } px_float PX_Object_Event_GetCursorY(PX_Object_Event e) { return e.Param_float[1]; } px_float PX_Object_Event_GetCursorZ(PX_Object_Event e) { return e.Param_float[2]; } px_float PX_Object_Event_GetCursorPressure(PX_Object_Event e) { return e.Param_float[3]; } px_int PX_Object_Event_GetCursorIndex(PX_Object_Event e) { return e.Param_int[2]; } px_float PX_Object_Event_GetWidth(PX_Object_Event e) { return e.Param_float[0]; } px_float PX_Object_Event_GetHeight(PX_Object_Event e) { return e.Param_float[1]; } px_int PX_Object_Event_GetIndex(PX_Object_Event e) { return e.Param_int[0]; } px_void PX_Object_Event_SetImpactTargetObject(PX_Object_Event* e, PX_Object* pObject) { e->Param_ptr[0] = (px_void *)pObject; } PX_Object* PX_Object_Event_GetImpactTargetObject(PX_Object_Event e) { return (PX_Object *)e.Param_ptr[0]; } px_int PX_Object_Event_GetInt(PX_Object_Event e) { return e.Param_int[0]; } px_void PX_Object_Event_SetWidth(PX_Object_Event *e,px_float w) { e->Param_float[0]=w; } px_void PX_Object_Event_SetHeight(PX_Object_Event *e,px_float h) { e->Param_float[1]=h; } px_void PX_Object_Event_SetCursorX(PX_Object_Event *e,px_float x) { e->Param_float[0]=x; } px_void PX_Object_Event_SetCursorY(PX_Object_Event *e,px_float y) { e->Param_float[1]=y; } px_void PX_Object_Event_SetCursorZ(PX_Object_Event *e,px_float z) { e->Param_float[2]=z; } px_void PX_Object_Event_SetCursorIndex(PX_Object_Event *e,px_int index) { e->Param_int[2]=index; } px_float PX_Object_Event_GetScaleCursorX(PX_Object_Event e) { return e.Param_float[0]; } px_float PX_Object_Event_GetScaleCursorY(PX_Object_Event e) { return e.Param_float[1]; } px_float PX_Object_Event_GetScaleCursorZ(PX_Object_Event e) { return e.Param_float[2]; } px_void PX_Object_Event_SetScaleCursorX(PX_Object_Event *e,px_float x) { e->Param_float[0]=x; } px_void PX_Object_Event_SetScaleCursorY(PX_Object_Event *e,px_float y) { e->Param_float[1]=y; } px_void PX_Object_Event_SetScaleCursorZ(PX_Object_Event *e,px_float z) { e->Param_float[2]=z; } px_uint PX_Object_Event_GetKeyDown(PX_Object_Event e) { return e.Param_uint[0]; } px_void PX_Object_Event_SetKeyDown(PX_Object_Event *e,px_uint key) { e->Param_uint[0]=key; } px_void PX_Object_Event_SetKeyUp(PX_Object_Event *e,px_uint key) { e->Param_uint[0]=key; } px_char* PX_Object_Event_GetStringPtr(PX_Object_Event e) { return (px_char *)e.Param_ptr[0]; } px_void* PX_Object_Event_GetDataPtr(PX_Object_Event e) { return (px_void *)e.Param_ptr[0]; } px_void PX_Object_Event_SetStringPtr(PX_Object_Event *e,px_void *ptr) { e->Param_ptr[0]=ptr; } px_void PX_Object_Event_SetDataPtr(PX_Object_Event *e,px_void *ptr) { e->Param_ptr[0]=ptr; } px_void PX_Object_Event_SetIndex(PX_Object_Event *e,px_int index) { e->Param_int[0]=index; } PX_Object * PX_ObjectCreate(px_memorypool *mp,PX_Object *Parent,px_float x,px_float y,px_float z,px_float Width,px_float Height,px_float Lenght) { PX_Object *pObject=(PX_Object *)MP_Malloc(mp,sizeof(PX_Object)); if (pObject==PX_NULL) { return PX_NULL; } PX_ObjectInitialize(mp,pObject,Parent,x,y,z,Width,Height,Lenght); return pObject; } PX_Object * PX_ObjectCreateEx(px_memorypool *mp,PX_Object *Parent,px_float x,px_float y,px_float z,px_float Width,px_float Height,px_float Lenght,px_int type,Function_ObjectUpdate Func_ObjectUpdate,Function_ObjectRender Func_ObjectRender,Function_ObjectFree Func_ObjectFree,px_void *desc,px_int size) { PX_Object *pObject=PX_ObjectCreate(mp,Parent,x,y,z,Width,Height,Lenght); if (pObject) { pObject->pObject=MP_Malloc(mp,size); if (!pObject->pObject) { MP_Free(mp,pObject); return PX_NULL; } if (desc) { PX_memcpy(pObject->pObject,desc,size); } else { PX_memset(pObject->pObject,0,size); } pObject->Type=type; pObject->Func_ObjectFree=Func_ObjectFree; pObject->Func_ObjectRender=Func_ObjectRender; pObject->Func_ObjectUpdate=Func_ObjectUpdate; } return pObject; } px_void PX_ObjectGetInheritXY(PX_Object *Object,px_float *x,px_float *y) { *x=0; *y=0; Object=Object->pParent; while (Object) { *x+=Object->x; *y+=Object->y; Object=Object->pParent; } } static px_void PX_Object_ObjectEventFree( PX_Object **Object ) { PX_OBJECT_EventAction *pNext,*pCur;; //PX_Object_Free Events linker pCur=(*Object)->pEventActions; while (pCur) { pNext=pCur->pNext; MP_Free((*Object)->mp,pCur); pCur=pNext; } (*Object)->pEventActions=PX_NULL; } static px_void PX_Object_ObjectFree( PX_Object *Object ) { PX_Object_ObjectEventFree(&Object); if (Object->Func_ObjectFree!=0) { Object->Func_ObjectFree(Object); } if(Object->pObject) MP_Free(Object->mp,Object->pObject); MP_Free(Object->mp,Object); } static px_void PX_Object_DeleteLinkerObject( PX_Object **ppObject ) { PX_Object *Object=(*ppObject); if (Object==PX_NULL) { return; } PX_Object_DeleteLinkerObject(&Object->pNextBrother); PX_Object_DeleteLinkerObject(&Object->pChilds); PX_Object_ObjectFree(Object); (*ppObject)=PX_NULL; } px_void PX_ObjectDelete( PX_Object *pObject ) { if (pObject==PX_NULL) { return; } if (pObject->OnFocus) { PX_ObjectClearFocus(pObject); } if (pObject->pChilds!=PX_NULL) { PX_Object_DeleteLinkerObject(&pObject->pChilds); } if (pObject->pParent!=PX_NULL) { if (pObject->pParent->pChilds==pObject) { pObject->pParent->pChilds=pObject->pNextBrother; if(pObject->pNextBrother) { pObject->pNextBrother->pParent=pObject->pParent; pObject->pNextBrother->pPreBrother=PX_NULL; } } else { if (pObject->pPreBrother!=PX_NULL) { pObject->pPreBrother->pNextBrother=pObject->pNextBrother; if(pObject->pNextBrother) pObject->pNextBrother->pPreBrother=pObject->pPreBrother; } else { PX_ERROR("Invalid Object struct"); } } } else { if (pObject->pPreBrother!=PX_NULL) { pObject->pPreBrother=pObject->pNextBrother; } } PX_Object_ObjectFree(pObject); } px_void PX_ObjectDelayDelete(PX_Object* pObject) { pObject->delay_delete = PX_TRUE; } px_void PX_ObjectDeleteChilds( PX_Object *pObject ) { if (pObject==PX_NULL) { return; } if (pObject->pChilds!=PX_NULL) { PX_Object_DeleteLinkerObject(&pObject->pChilds); } } px_void PX_Object_ObjectLinkerUpdate( PX_Object *pObject,px_uint elapsed) { if (pObject==PX_NULL) { return; } if (pObject->Enabled) { if (pObject->Func_ObjectUpdate!=0) { pObject->Func_ObjectUpdate(pObject,elapsed); } if (!pObject->delay_delete) { PX_Object_ObjectLinkerUpdate(pObject->pChilds, elapsed); } } PX_Object_ObjectLinkerUpdate(pObject->pNextBrother,elapsed); } static px_void PX_ObjectUpdateDelayDelete(PX_Object* pObject) { if (pObject==PX_NULL) { return; } PX_ObjectUpdateDelayDelete(pObject->pNextBrother); if (pObject->delay_delete) { PX_ObjectDelete(pObject); } else { PX_ObjectUpdateDelayDelete(pObject->pChilds); } } px_void PX_ObjectUpdate(PX_Object *pObject,px_uint elapsed ) { if (pObject==PX_NULL) { PX_ASSERT(); return; } if (pObject->Enabled==PX_FALSE) { return; } if (pObject->Func_ObjectUpdate!=0) { pObject->Func_ObjectUpdate(pObject,elapsed); } if (pObject->pChilds!=PX_NULL&&!pObject->delay_delete) { PX_Object_ObjectLinkerUpdate(pObject->pChilds,elapsed); } if (pObject->delay_delete) { PX_ObjectDelete(pObject); } else { PX_ObjectUpdateDelayDelete(pObject->pChilds); } } static px_void PX_ObjectRenderEx(px_surface *pSurface, PX_Object *pObject,px_uint elapsed ) { if (pObject==PX_NULL) { return; } if (pObject->OnFocus) { PX_ObjectRenderEx(pSurface,pObject->pNextBrother,elapsed); if (pObject->Visible!=PX_FALSE) { if (pObject->Width>=0&&pObject->Height>=0) { if (pObject->Func_ObjectBeginRender) { pObject->Func_ObjectBeginRender(pSurface, pObject, elapsed); } if (pObject->Func_ObjectRender != 0) { pObject->Func_ObjectRender(pSurface, pObject, elapsed); } } PX_ObjectRenderEx(pSurface,pObject->pChilds,elapsed); if (pObject->Width >= 0 && pObject->Height >= 0) { if (pObject->Func_ObjectEndRender) { pObject->Func_ObjectEndRender(pSurface, pObject, elapsed); } } } } else { if (pObject->Visible!=PX_FALSE) { if (pObject->Width >= 0 && pObject->Height >= 0) { if (pObject->Func_ObjectBeginRender) { pObject->Func_ObjectBeginRender(pSurface, pObject, elapsed); } if (pObject->Func_ObjectRender != 0) { pObject->Func_ObjectRender(pSurface, pObject, elapsed); } } PX_ObjectRenderEx(pSurface,pObject->pChilds,elapsed); if (pObject->Width >= 0 && pObject->Height >= 0) { if (pObject->Func_ObjectEndRender) { pObject->Func_ObjectEndRender(pSurface, pObject, elapsed); } } } PX_ObjectRenderEx(pSurface,pObject->pNextBrother,elapsed); } } px_void PX_ObjectRender(px_surface *pSurface, PX_Object *pObject,px_uint elapsed ) { if (pObject==PX_NULL) { return; } if (pObject->OnFocus) { if (pObject->Visible!=PX_FALSE) { if (pObject->Func_ObjectBeginRender) { pObject->Func_ObjectBeginRender(pSurface,pObject,elapsed); } if (pObject->Func_ObjectRender!=0) { pObject->Func_ObjectRender(pSurface,pObject,elapsed); } if (!pObject->delay_delete) { PX_ObjectRenderEx(pSurface, pObject->pChilds, elapsed); } if (pObject->Func_ObjectEndRender) { pObject->Func_ObjectEndRender(pSurface,pObject,elapsed); } } } else { if (pObject->Visible!=PX_FALSE) { if (pObject->Func_ObjectBeginRender) { pObject->Func_ObjectBeginRender(pSurface,pObject,elapsed); } if (pObject->Func_ObjectRender!=0) { pObject->Func_ObjectRender(pSurface,pObject,elapsed); } if (!pObject->delay_delete) { PX_ObjectRenderEx(pSurface, pObject->pChilds, elapsed); } if (pObject->Func_ObjectEndRender) { pObject->Func_ObjectEndRender(pSurface,pObject,elapsed); } } } if (pObject->delay_delete) { PX_ObjectDelete(pObject); } else { PX_ObjectUpdateDelayDelete(pObject->pChilds); } } px_bool PX_ObjectIsPointInRegion( PX_Object *pObject,px_float x,px_float y ) { px_float objx,objy,objw,objh,r; px_float inheritX,inheritY; PX_ObjectGetInheritXY(pObject,&inheritX,&inheritY); objx=(pObject->x+inheritX); objy=(pObject->y+inheritY); objw=pObject->Width; objh=pObject->Height; r = pObject->diameter/2; if (r) return PX_isPoint2DInCircle(PX_POINT2D(x,y),PX_POINT2D(objx,objy),r); else return PX_isXYInRegion(x,y,objx,objy,objw,objh); } px_bool PX_ObjectIsCursorInRegion(PX_Object *Object,PX_Object_Event e) { return PX_ObjectIsPointInRegion(Object,PX_Object_Event_GetCursorX(e),PX_Object_Event_GetCursorY(e)); } px_float PX_ObjectGetHeight(PX_Object *Object) { return Object->Height; } px_float PX_ObjectGetWidth(PX_Object *Object) { return Object->Width; } px_void PX_ObjectAddChild(PX_Object *Parent,PX_Object *child) { PX_Object *pLinker; child->pParent=Parent; if(Parent->pChilds==PX_NULL) { Parent->pChilds=child; } else { pLinker=Parent->pChilds; while (pLinker->pNextBrother) { pLinker=pLinker->pNextBrother; } pLinker->pNextBrother=child; child->pPreBrother=pLinker; } child->pNextBrother=PX_NULL; } px_void PX_ObjectInitialize(px_memorypool *mp,PX_Object *pObject,PX_Object *Parent,px_float x,px_float y,px_float z,px_float Width,px_float Height,px_float Lenght ) { PX_memset(pObject,0,sizeof(PX_Object)); pObject->x=x; pObject->y=y; pObject->z=z; pObject->Width=Width; pObject->Height=Height; pObject->Enabled=PX_TRUE; pObject->Visible=PX_TRUE; pObject->pChilds=PX_NULL; pObject->pObject=PX_NULL; pObject->pNextBrother=PX_NULL; pObject->pPreBrother=PX_NULL; pObject->Type=PX_OBJECT_TYPE_NULL; pObject->ReceiveEvents=PX_TRUE; pObject->impact_target_type=0; pObject->impact_object_type=0; pObject->pEventActions=PX_NULL; pObject->world_index=-1; pObject->User_int=0; pObject->diameter=0; pObject->User_ptr=PX_NULL; pObject->OnFocus=PX_FALSE; pObject->mp=mp; pObject->Func_ObjectFree=PX_NULL; pObject->Func_ObjectRender=PX_NULL; pObject->Func_ObjectUpdate=PX_NULL; pObject->Func_ObjectLinkChild=PX_NULL; pObject->Func_ObjectBeginRender=PX_NULL; pObject->Func_ObjectEndRender=PX_NULL; if (Parent!=PX_NULL) { if (Parent->Func_ObjectLinkChild!=PX_NULL) { Parent->Func_ObjectLinkChild(Parent,pObject); } else { PX_ObjectAddChild(Parent,pObject); } } } px_void PX_ObjectSetId(PX_Object *pObject,const px_char id[]) { PX_strcpy(pObject->id,id,sizeof(pObject->id)); } px_void PX_ObjectSetVisible( PX_Object *pObject,px_bool visible ) { if(pObject!=PX_NULL) { if (pObject->OnFocus) { PX_ObjectClearFocus(pObject); } pObject->Visible=visible; } } px_void PX_ObjectSetEnabled(PX_Object *Object,px_bool enabled) { Object->Enabled=enabled; } px_void PX_ObjectEnable(PX_Object *Object) { Object->Enabled=PX_TRUE; } px_void PX_ObjectDisable(PX_Object *Object) { Object->Enabled=PX_FALSE; } px_int PX_ObjectRegisterEvent( PX_Object *Object,px_uint Event,px_void (*ProcessFunc)(PX_Object *,PX_Object_Event e,px_void *user_ptr),px_void *user) { PX_OBJECT_EventAction *pPoint; PX_OBJECT_EventAction *pAction=(PX_OBJECT_EventAction *)MP_Malloc(Object->mp,sizeof(PX_OBJECT_EventAction)); if (pAction==PX_NULL) { return PX_FALSE; } pAction->pNext=PX_NULL; pAction->pPre=PX_NULL; pAction->EventAction=Event; pAction->EventActionFunc=ProcessFunc; pAction->user_ptr=user; pPoint=Object->pEventActions; if (pPoint==PX_NULL) { Object->pEventActions=pAction; return PX_TRUE; } while(pPoint->pNext) { pPoint=pPoint->pNext; } pAction->pPre=pPoint; pPoint->pNext=pAction; return PX_TRUE; } px_void PX_ObjectExecuteEvent(PX_Object *pPost,PX_Object_Event Event) { PX_OBJECT_EventAction *EventAction; if (pPost->Visible==PX_FALSE||pPost->Enabled==PX_FALSE||pPost->ReceiveEvents==PX_FALSE) { return; } EventAction=pPost->pEventActions; while(EventAction) { if (EventAction->EventAction==PX_OBJECT_EVENT_ANY||EventAction->EventAction==Event.Event) { EventAction->EventActionFunc(pPost,Event,EventAction->user_ptr); } EventAction=EventAction->pNext; } } px_bool PX_ObjectPostEventLink( PX_Object *pPost,PX_Object_Event Event ) { if (pPost==PX_NULL) { return PX_TRUE; } if (pPost->Visible==PX_FALSE||pPost->Enabled==PX_FALSE||pPost->ReceiveEvents==PX_FALSE) { if(PX_ObjectPostEventLink(pPost->pNextBrother,Event)==PX_FALSE) return PX_FALSE; return PX_TRUE; } if (pPost->OnFocus) { if(PX_ObjectPostEventLink(pPost->pChilds,Event)==PX_FALSE) { return PX_FALSE; } else { PX_ObjectExecuteEvent(pPost,Event); } if (!pPost->OnFocus&&!pPost->OnLostFocusReleaseEvent) { return PX_ObjectPostEventLink(pPost->pNextBrother,Event); } return PX_FALSE; } else { if(PX_ObjectPostEventLink(pPost->pNextBrother,Event)==PX_FALSE) return PX_FALSE; if(PX_ObjectPostEventLink(pPost->pChilds,Event)==PX_FALSE) return PX_FALSE; PX_ObjectExecuteEvent(pPost,Event); if (pPost->OnFocus) { return PX_FALSE; } return PX_TRUE; } } px_void PX_ObjectPostEvent( PX_Object *pPost,PX_Object_Event Event ) { if (pPost==PX_NULL) { return; } if (pPost->Visible==PX_FALSE||pPost->Enabled==PX_FALSE||pPost->ReceiveEvents==PX_FALSE) { return; } if (pPost->OnFocus) { if(PX_ObjectPostEventLink(pPost->pChilds,Event)==PX_FALSE) { if (!pPost->OnFocus) { PX_ObjectExecuteEvent(pPost,Event); } } else { PX_ObjectExecuteEvent(pPost,Event); } return; } else { if(PX_ObjectPostEventLink(pPost->pChilds,Event)==PX_FALSE) return; PX_ObjectExecuteEvent(pPost,Event); return; } } px_void PX_ObjectSetPosition( PX_Object *Object,px_float x,px_float y,px_float z) { if (Object==PX_NULL) { PX_ASSERT(); return; } Object->x=x; Object->y=y; Object->z=z; } px_void PX_ObjectSetSize( PX_Object *Object,px_float Width,px_float Height,px_float length) { if (Object!=PX_NULL) { Object->Width=Width; Object->Height=Height; } else { PX_ASSERT(); } } px_void PX_ObjectSetUserCode(PX_Object *pObject,px_int user) { pObject->User_int=user; } px_void PX_ObjectSetUserPointer(PX_Object *pObject,px_void *user_ptr) { pObject->User_ptr=user_ptr; } px_void PX_ObjectSetParent(PX_Object* pObject, PX_Object* pParent) { if (pObject == PX_NULL) return; if (pObject->pParent == pParent) return; if (pObject->OnFocus) PX_ObjectClearFocus(pObject); // detach from parent if (pObject->pParent != PX_NULL) { if (pObject->pParent->pChilds == pObject) { pObject->pParent->pChilds = pObject->pNextBrother; if (pObject->pNextBrother) { pObject->pNextBrother->pParent = pObject->pParent; pObject->pNextBrother->pPreBrother = PX_NULL; } } else { if (pObject->pPreBrother != PX_NULL) { pObject->pPreBrother->pNextBrother = pObject->pNextBrother; if (pObject->pNextBrother) pObject->pNextBrother->pPreBrother = pObject->pPreBrother; } else { PX_ERROR("Invalid Object struct"); } } } else { if (pObject->pPreBrother != PX_NULL) { pObject->pPreBrother = pObject->pNextBrother; } } // if the parent is null, then the object is a root object if (pParent == PX_NULL) { pObject->pParent = PX_NULL; pObject->pNextBrother = PX_NULL; pObject->pPreBrother = PX_NULL; } else { PX_ObjectAddChild(pParent, pObject); } } ////////////////////////////////////////////////////////////////////////// px_bool PX_Designer_GetID(PX_Object* pObject, px_string* str) { PX_StringSet(str, pObject->id); return PX_TRUE; } px_void PX_Designer_SetID(PX_Object* pObject, const px_char id[]) { PX_ObjectSetId(pObject, id); } px_float PX_Designer_GetX(PX_Object* pObject) { return pObject->x; } px_float PX_Designer_GetY(PX_Object* pObject) { return pObject->y; } px_float PX_Designer_GetWidth(PX_Object* pObject) { return pObject->Width; } px_float PX_Designer_GetHeight(PX_Object* pObject) { return pObject->Height; } px_bool PX_Designer_GetEnable(PX_Object* pObject) { return pObject->Enabled; } px_void PX_Designer_SetX(PX_Object* pObject, px_float v) { pObject->x = v; } px_void PX_Designer_SetY(PX_Object* pObject, px_float v) { pObject->y = v; } px_void PX_Designer_SetWidth(PX_Object* pObject, px_float v) { pObject->Width = v; } px_void PX_Designer_SetEnable(PX_Object* pObject, px_bool v) { pObject->Enabled = v; } px_void PX_Designer_SetHeight(PX_Object* pObject, px_float v) { pObject->Height = v; }
C
#include<stdio.h> int main() { printf("hello, I'm %s and i'm %d\n", "Duc Anh", 20); return 0; }
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* sortList(ListNode* head) { return mergeSort(head); } ListNode* mergeSort(ListNode* head){ if (!head||!head->next) return head; ListNode *walker, *runner; walker = head; runner = head; while(runner->next&&runner->next->next){ walker = walker->next; runner = runner->next->next; } ListNode* head1 = head; ListNode* head2 = walker->next; walker->next = nullptr; head1 = mergeSort(head1); head2 = mergeSort(head2); return mySort(head1, head2); } ListNode* mySort(ListNode *head1, ListNode *head2){ ListNode* helper; if (!head1&&!head2) return head1; if (!head1) return head2; if (!head2) return head1; ListNode* head, *node, *l1next, *l2next; l1next = head1; l2next = head2; if (l1next->val<=l2next->val){ head = l1next; l1next = l1next->next; } else{ head = l2next; l2next = l2next->next; } node = head; while(l1next && l2next){ if (l1next->val<=l2next->val){ node->next = l1next; l1next = l1next->next; } else{ node->next = l2next; l2next = l2next->next; } node = node->next; } node->next = l1next?l1next:l2next; return head; } };
C
#ifdef __linux__ #include <stdio.h> #include <sys/time.h> /* for gettimeofday */ #include <string.h> /* for memset */ #include "../linux/linuxcompat.h" #include "../linux/bline.h" #else #include "colors.h" #include "menu.h" #include "buttons.h" #include "fb.h" /* TODO: I shouldn't have to declare these myself. */ #define size_t int extern char *strcpy(char *dest, const char *src); extern char *strncpy(char *dest, const char *src, size_t n); extern void *memset(void *s, int c, size_t n); extern char *strcat(char *dest, const char *src); #endif #include "dynmenu.h" void dynmenu_init(struct dynmenu *dm, struct dynmenu_item *item, unsigned char max_items) { dm->item = item; dm->max_items = max_items; } void dynmenu_set_colors(struct dynmenu *dm, int color, int selected_color) { dm->color = color; dm->selected_color = selected_color; } void dynmenu_clear(struct dynmenu *dm) { dm->title[0] = '\0'; dm->title2[0] = '\0'; dm->title3[0] = '\0'; dm->nitems = 0; dm->current_item = 0; dm->menu_active = 0; dm->chosen_cookie = 0; } #define ARRAYSIZE(x) (sizeof((x)) / sizeof((x)[0])) void dynmenu_add_item(struct dynmenu *dm, char *text, int next_state, unsigned char cookie) { int i; if (dm->nitems >= dm->max_items) { #ifdef linux printf("WARNING: dynmenu_add_item: failed to add menu item, max_items = %d\n", dm->max_items); #endif return; } i = dm->nitems; strncpy(dm->item[i].text, text, sizeof(dm->item[i].text) - 1); dm->item[i].next_state = next_state; dm->item[i].cookie = cookie; dm->nitems++; } void dynmenu_draw(struct dynmenu *dm) { int i, y, first_item, last_item; first_item = dm->current_item - 3; if (first_item < 0) first_item = 0; last_item = dm->current_item + 3; if (last_item > dm->nitems - 1) last_item = dm->nitems - 1; FbClear(); FbColor(WHITE); FbMove(8, 5); FbWriteLine(dm->title); if (dm->title2[0] != '\0') { FbMove(8, 12); FbWriteLine(dm->title2); } if (dm->title3[0] != '\0') { FbMove(8, 19); FbWriteLine(dm->title3); } y = LCD_YSIZE / 2 - 10 * (dm->current_item - first_item); for (i = first_item; i <= last_item; i++) { if (i == dm->current_item) FbColor(GREEN); else FbColor(WHITE); FbMove(10, y); FbWriteLine(dm->item[i].text); y += 10; } FbColor(GREEN); FbMove(5, LCD_YSIZE / 2 - 2); FbRectangle(LCD_XSIZE - 7, 12); } void dynmenu_change_current_selection(struct dynmenu *dm, int direction) { int new = dm->current_item + direction; if (new < 0) new = dm->nitems - 1; else if (new >= dm->nitems) new = 0; dm->current_item = new; }
C
/** * Write an efficient algorithm that searches for a value in an m x n matrix. * This matrix has the following properties: * - Integers in each row are sorted from left to right. * - The first integer of each row is greater than the last integer of the * previous row. * * Example: * Input: * matrix = [ * [1, 3, 5, 7], * [10, 11, 16, 20], * [23, 30, 34, 50] * ] * target = 13 * Output: false * * 在二维矩阵中查找指定元素.题设给出矩阵的每行元素从左到右升序排列,且每行的 * 第一个元素比上一行的最后一个元素大. * 在已排序的元素中查找,自然就是binary search了,不过此处是一个矩阵,需要先确 * 定元素位于哪一行,然后在确定在哪一列. */ bool searchMatrix(int **matrix, int matrixRowSize, int matrixColSize, int target) { int up, down, left, right, row_center, col_center; if (matrixRowSize == 0 || matrixColSize == 0) return false; up = 0; down = matrixRowSize - 1; while (up < down) { row_center = (up + down) / 2; if (matrix[row_center][0] <= target) up = row_center + 1; else if (matrix[row_center][0] > target) down = row_center - 1; } /* 判断是否找到target. * 1. 若找到target,直接返回. * 2. 若没找到target,此时要判断matrix[up][0]处的值与target的关系: * a. 若该值大于target,则应该在第up - 1行继续搜索; * b. 若该值小于target,则应该在当前行继续搜索; */ if (matrix[up][0] == target) return true; else if (up > 0 && matrix[up][0] > target) up -= 1; left = 0; right = matrixColSize - 1; while (left < right) { col_center = (left + right) / 2; if (matrix[up][col_center] < target) left = col_center + 1; else right = col_center; } return matrix[up][left] == target; } /** * 上述方法的空间复杂度是O(1).既然题设假定给定的矩阵每行是排序的且每行第一个 * 元素都比上一行的最后一个元素大,可以开一个m x n大小的数组来存储矩阵元素.剩 * 下的事情就是简单的binary search了. */ int compare(void *a, void *b) { return *(int *)a - *(int *)b; } bool searchMatrix(int **matrix, int matrixRowSize, int matrixColSize, int target) { int *array, i; array = (int *)malloc(matrixRowSize * matrixColSize * sizeof(int)); for (i = 0; i < matrixRowSize; ++i) memcpy(array + i * matrixColSize, matrix[i], matrixColSize * sizeof(int)); return bsearch(&target, array, matrixRowSize * matrixColSize, sizeof(int), compare); }
C
#include <stdio.h> #include <stdlib.h> #define ERROR_FILE_OPEN -3 int main(void) { long long int address = 0x00000000004011d2; unsigned char *sd; FILE *output = NULL; char number = '1'; output = fopen("output.bin", "wb"); if (output == NULL) { printf("Error opening file"); exit(ERROR_FILE_OPEN); } for(int i = 0; i < 20; i++) { fwrite(&number, sizeof(char), 1, output); } sd = (char*)&address; for(int i = 0; i < 8; i++) { fwrite(sd,sizeof(char), 1, output); sd++; } fclose(output); }
C
#include <stdio.h> int readInt() // Funktion zum Einlesen der Tastatureingabe { int number; scanf("%d", &number); return number; } int abs(int x) // Funktion zum Bestimmen des Betrags einer Zahl { int betrag; if (x < 0) betrag = -x; else betrag = x; return betrag; } int Sternenraster (int maxZiffer) // Funktion zur Ausgabe des Sternenrasters { int Zeichen, AnzahlLeer, AnzahlZeile; int Zeilenabstand = 0; while (Zeilenabstand < 26) { Zeichen = 0; while (Zeichen < 51) { printf("*"); Zeichen = Zeichen +1; AnzahlLeer = maxZiffer - 1; while (AnzahlLeer > 0) { printf(" "); Zeichen = Zeichen +1; AnzahlLeer = AnzahlLeer - 1; } } AnzahlZeile = maxZiffer; while (AnzahlZeile > 0) { printf("\n"); Zeilenabstand = Zeilenabstand + 1; AnzahlZeile = AnzahlZeile - 1; } } } int Minimum (int min, int number) // Bestimmung des Minimum von zwei Zahlen { if (min < number) return min; else return number; } int Maximum(int max, int number) // Bestimmung des Maximums von zwei Zahlen { if (max > number) return max; else return number; } int BestimmungZiffernzahl (int number) // Bestimmung der Ziffernanzahl einer Zahl { int Ziffern = 0; number = abs(number); while (number > 0) { number = number / 10; Ziffern = Ziffern +1; } return Ziffern; } int main () { int number, Summe = 0, n = 0, Mittelwert, ZiffernZahl, maxZiffer = 0, maxAbweichung; printf("Zahlenfolge: "); number = readInt(); int max = number; int min = number; while (number != 0 ) { Summe = Summe + number; n = n + 1; Mittelwert = Summe / n; max = Maximum (max, number); min = Minimum (min, number); ZiffernZahl = BestimmungZiffernzahl(number); maxZiffer = Maximum (maxZiffer, ZiffernZahl); number = readInt(); }; maxAbweichung = Maximum(abs(Mittelwert - min),abs (Mittelwert - max)); printf("Mittelwert der Folge: %d\nGroesste Abweichung zum Mittelwert: %d\nMaximale Ziffernanzahl: %d\n", Mittelwert, maxAbweichung, maxZiffer); Sternenraster (maxZiffer); return 0; }
C
/* inches.c */ #include "inches.h" double cnv_dm_ft(const double n) { //Дюймы в футы return(n/12); } double cnv_dm_yd(const double n) { return(n/36); } double cnv_dm_ml(const double n) { return(n/63360); } double cnv_ft_dm(const double n) { //Футы в дюймы return(n*12); } double cnv_ft_yd(const double n) { return(n/3); } double cnv_ft_ml(const double n) { return(n/5280); } double cnv_yd_dm(const double n) { //Ярды в дюймы return(n*36); } double cnv_yd_ft(const double n) { return(n*3); } double cnv_yd_ml(const double n) { return(n/1760); } double cnv_ml_dm(const double n) { //Мили в дюймы return(n*63360); } double cnv_ml_ft(const double n) { return(n*5280); } double cnv_ml_yd(const double n) { return(n*1760); } /* EOF */
C
#include<stdio.h> #include<conio.h> void main() { int min,hr; scanf("%d",&min); hr=min/60; min=min%60; printf("%d\t%d",hr,min); getch(); }
C
// Converts gsl matrix to double precision nr matrix and creates new pointer // to pointer. #define GSL2NRDM1(d, m, p, s) double* d[m->size1+1]; \ { \ int port_i; \ for(port_i = s; port_i <= (int)m->size1; port_i++) { \ d[port_i+1] = m->data + port_i*m->size2 - 1; \ } \ } \ double** p = d; // Converts gsl matrix to double precision nr matrix and assigns to already // existing pointer to pointer. #define GSL2NRDM2(d, m, p, s) double* d[m->size1+1]; \ { \ int port_i; \ for(port_i = s; port_i <= (int)m->size1; port_i++) { \ d[port_i+1] = m->data + port_i*m->size2 - 1; \ } \ } \ p = d; // Sets values of gsl matrix from an array of data. #define GSLSET(data, mat, n, m, nn, mm) \ { \ int port_i, port_j; \ for (port_i = n; port_i < nn; port_i++) \ for (port_j = m; port_j < mm; port_j++) \ gsl_matrix_set (mat, port_i, port_j, data[port_i][port_j]); \ } // Sets values of gsl matrix from nr matrix. #define GSLSET2(nr, mat, n, m, nn, mm) \ { \ int port_i, port_j; \ for (port_i = n; port_i < nn; port_i++) \ for (port_j = m; port_j < mm; port_j++) \ gsl_matrix_set (mat, port_i, port_j, nr[port_i+1][port_j+1]); \ } // Prints gsl matrix to standard output. #define GSLPRINT(x, n, m, nn, mm) \ { \ int port_i, port_j; \ for ( port_i = n; port_i < nn; port_i++) { \ for ( port_j = m; port_j < mm; port_j++) { \ printf("%g ", gsl_matrix_get(x, port_i, port_j)); \ } \ printf("\n"); \ } \ } // Prints nr matrix to standard output . #define NRPRINT(x, n, m, nn, mm) \ { \ int port_i, port_j; \ for ( port_i = n; port_i <= nn; port_i++ ) { \ for ( port_j = m; port_j <= mm; port_j++ ) { \ printf("%g ", x[port_i][port_j]); \ } \ printf("\n"); \ } \ } // Converts gsl vector to double nr vector and creates pointer to it. #define GSL2NRDV1(v, p) double *p = v->data-1; // Converts gsl vector to double nr vector. #define GSL2NRDV2(v, p) p = v->data-1; double ***gslport_tensor(int t1, int t2, int r1, int r2, int s1, int s2); long unsigned int *gslport_lvector(int s, int e); void gslport_matrixdump( FILE *outf, char *text, gsl_matrix *m, char *format);
C
#include<stdio.h> #include<conio.h> int main() { int i,n,arr[20]; printf("\n Enter the elements of an array : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n arr[%d] = ", i); scanf("%d",&arr[i]); } printf("\n The array of elements are "); for(i=0;i<n;i++) printf("\t %d",arr[i]); return 0; }
C
#include <stdio.h> #include <stdlib.h> void taban(int sayi,int cevir) { int i,j; int dizi[100]; for (i=0;sayi!=0;i++) { dizi[i]=sayi%cevir; sayi=sayi/cevir; } for(j=i-1;j>=0;j--) printf("%d",dizi[j]); } int main() { int sayi,cevir; printf("cevirmek istediginiz sayiyi giriniz:"); scanf("%d",&sayi); printf("cevirmek istediginiz tabani giriniz:"); scanf("%d",&cevir); taban(sayi,cevir); return 0; }
C
#include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> void print_statistics (const char * fname, struct stat * st) { printf ("FILE:\t\t%s\n", fname); printf ("UID:\t\t%d\n", (int) st->st_uid); printf ("GID:\t\t%d\n", (int) st->st_gid); printf ("SIZE:\t\t%ld\n", (long int) st->st_size); printf ("AT:\t\t%s", ctime (&st->st_atime)); printf ("MT:\t\t%s", ctime (&st->st_mtime)); } int main (int argc, char ** argv) { struct stat st; if (argc < 2) { fprintf (stderr, "Too few arguments\n"); return 1; } if (stat (argv[1], &st) == -1) { fprintf (stderr, "stat() error\n"); return 1; } printf ("-- STAT() --\n"); print_statistics (argv[1], &st); if (lstat (argv[1], &st) == -1) { fprintf (stderr, "lstat() error\n"); return 1; } printf ("-- LSTAT() --\n"); print_statistics (argv[1], &st); return 0; }
C
#include <stdio.h> #include "libpoint.h" void drawborder(int left, int right, int height) { while (--height > 0) { setcol(left); printf("+"); setcol(right - left - 1); printf("+"); printf("\n"); } }
C
#ifndef _cbuffer_h_ #define _cbuffer_h_ #include <stdint.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif struct cbuffer_t { uint8_t* ptr; size_t len; size_t cap; size_t limit; }; static inline void cbuffer_init(struct cbuffer_t* cb) { memset(cb, 0, sizeof(*cb)); cb->limit = 0x80000000U; } static inline void cbuffer_free(struct cbuffer_t* cb) { if (cb && cb->ptr) { assert(cb->cap > 0); free(cb->ptr); cb->ptr = NULL; cb->len = cb->cap = 0; } } static inline int cbuffer_resize(struct cbuffer_t* cb, size_t bytes) { uint8_t* ptr; if (bytes <= cb->cap) return 0; if (bytes > cb->limit) return -1; bytes += bytes / 4; bytes = bytes > cb->limit ? cb->limit : bytes; ptr = (uint8_t*)realloc(cb->ptr, bytes); if (!ptr) return -1; // ENOMEM cb->ptr = ptr; cb->cap = bytes; return 0; } static inline int cbuffer_append(struct cbuffer_t* cb, const void* data, size_t bytes) { if (cb->len + bytes > cb->cap && 0 != cbuffer_resize(cb, cb->len + bytes)) return -1; memmove(cb->ptr + cb->len, data, bytes); cb->len += bytes; return (int)cb->len; } static inline int cbuffer_insert(struct cbuffer_t* cb, size_t off, const void* data, size_t bytes) { if (off > cb->len) return -1; if (cb->len + bytes > cb->cap && 0 != cbuffer_resize(cb, cb->len + bytes)) return -1; memmove(cb->ptr + off + bytes, cb->ptr + off, cb->len - off); memmove(cb->ptr + off, data, bytes); cb->len += bytes; return (int)cb->len; } static inline int cbuffer_remove(struct cbuffer_t* cb, size_t off, size_t bytes) { if (off + bytes > cb->len) return -1; memmove(cb->ptr + off, cb->ptr + off + bytes, cb->len - off - bytes); cb->len -= bytes; return (int)cb->len; } #ifdef __cplusplus } #endif #endif /* !_cbuffer_h_ */
C
#include "includes/shmem.h" static sem_t * public_sem_wr = NULL; static sem_t * public_sem_rd = NULL; void IPC_init(int pid, char * ipc_path) { if(pid == SERVER) { char public_path_wr[PATH_SIZE]; char public_path_rd[PATH_SIZE]; sprintf(public_path_wr, "%s%s", ipc_path, "wr"); sprintf(public_path_rd, "%s%s", ipc_path, "rd"); public_sem_wr = sem_open(public_path_wr, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, 1); public_sem_rd = sem_open(public_path_rd, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, 0); } else { char private_path[PATH_SIZE]; sprintf(private_path, "%s%d", ipc_path, pid); sem_open(private_path, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, 0); } } int IPC_connect(int pid, char * ipc_path) { int shmid; if ((shmid = shmget(pid, sizeof(message_t), 0666 | IPC_CREAT)) == -1) { printf("Couldn't allocate shared memory\n"); exit(-1); } if(pid == SERVER) { char public_path_wr[PATH_SIZE]; char public_path_rd[PATH_SIZE]; sprintf(public_path_wr, "%s%s", ipc_path, "wr"); sprintf(public_path_rd, "%s%s", ipc_path, "rd"); public_sem_wr = sem_open(public_path_wr, O_CREAT); public_sem_rd = sem_open(public_path_rd, O_CREAT); } return shmid; } void IPC_close(int fd, char * ipc_path, int pid) { if(pid == SERVER) { char public_path_wr[PATH_SIZE]; char public_path_rd[PATH_SIZE]; sprintf(public_path_wr, "%s%s", ipc_path, "wr"); sprintf(public_path_rd, "%s%s", ipc_path, "rd"); sem_close(public_sem_wr); sem_unlink(public_path_wr); sem_close(public_sem_rd); sem_unlink(public_path_rd); } else { char private_path[PATH_SIZE]; sprintf(private_path, "%s%d", "/ipc", pid); sem_t * private_sem = sem_open(private_path, O_CREAT); sem_close(private_sem); sem_unlink(private_path); } close(fd); shmctl(fd, IPC_RMID, NULL); } void IPC_send(message_t msg, int fd, int pid) { if(pid == SERVER) { sem_wait(public_sem_wr); copyFromMsg(fd, &msg); sem_post(public_sem_rd); } else { char private_path[PATH_SIZE]; sprintf(private_path, "%s%d", "/ipc", pid); sem_t * private_sem = sem_open(private_path, O_CREAT); copyFromMsg(fd, &msg); sem_post(private_sem); } } message_t IPC_receive(int fd, int pid) { message_t message; if(pid == SERVER) { sem_wait(public_sem_rd); copyToMsg(fd, &message); sem_post(public_sem_wr); } else { char private_path[PATH_SIZE]; sprintf(private_path, "%s%d", "/ipc", pid); sem_t * private_sem = sem_open(private_path, O_CREAT); sem_wait(private_sem); copyToMsg(fd, &message); } return message; } void copyToMsg(int fd, message_t * message) { void * memory; memory = shmat(fd, NULL, 0); memcpy(message, memory, sizeof(message_t)); shmdt(memory); } void copyFromMsg(int fd, message_t * message) { void * memory; memory = shmat(fd, NULL, 0); memcpy(memory, message, sizeof(message_t)); shmdt(memory); }
C
/* * Frame.c * * Created on: Mar 22, 2018 * Author: okh */ #include "crypt.h" #include "frame.h" #include "config.h" const string_t OK = "OK;"; /*Специфичные для протокола определения размеров*/ #define CRC_SIZE 2 static const char startByte = '$'; static u16 crc16(u16 size, byte_ptr data) { return CRC16(size, data); } #ifndef NULL #define NULL 0 #endif static s16 findByte(u08 byte, byte_ptr src, u08 maxSize) { if(src == NULL) return -1; u08 i = 0; while(src[i] != byte && i<maxSize) i++; if(i == maxSize) return -1; return (s16)i; } #include "logging.h" /* * 8 байт оверхеда * $ (isSecure<<7) | 'MessgeType' 'messageID' 'dataSize' 'deviceID' "MESSAGE" CRC * */ static u16 parseFrameBinary(const u16 sourceSize, const byte_ptr source, message_t* result) { if(result == NULL || result->data == NULL || result->dataSize == 0) return 0; s16 poz = findByte(startByte, source, 5); //findSymb(startByte,(const string_t)source); if(poz < 0) { writeLogStr("Undefined start symbol $"); return 0; // Не нашли стартовый символ } u08 savePoz = (u08)poz; result->messageType = source[++poz]&0x7F; result->isSecure = (bool_t)(source[poz] >> 7); result->messageID = source[++poz]; u16 allMessageSize = source[++poz]; if(sourceSize < allMessageSize) return 0; // Не получено ВСЕ сообщение u08 effectiveMessageSize = allMessageSize - sizeof(result->deviceID) - CRC_SIZE; result->deviceID = source[++poz]; result->deviceID |= ((u16)source[++poz]<<8); u16 crcShift = sizeof(startByte)+sizeof(result->messageType)+sizeof(result->messageID)+sizeof(result->dataSize)+allMessageSize-CRC_SIZE; u16 calcCRC = crc16(crcShift, source+savePoz); u16 reqCRC = source[savePoz+crcShift] | ((u16)source[savePoz+crcShift+1] << 8); if(calcCRC == reqCRC) { if(result->dataSize > effectiveMessageSize) { memCpy(result->data,source+poz+1,effectiveMessageSize); memSet(result->data+effectiveMessageSize,result->dataSize-effectiveMessageSize,0); return effectiveMessageSize; } else { memCpy(result->data,source+poz+1,result->dataSize); return result->dataSize; } } writeLogStr("Incorrect checksum"); result->deviceID = 0; return 0; } /* * 8 байт оверхеда * $ (isSecure<<7) | 'MessgeType' 'messageID' 'dataSize' 'deviceID' "MESSAGE" CRC * */ static u16 formFrameBinary(const u16 maxSize, byte_ptr result, const message_t*const msg) { if( sizeof(startByte)+sizeof(msg->messageType)+sizeof(msg->messageID)+sizeof(msg->dataSize)+sizeof(msg->deviceID) + CRC_SIZE + msg->dataSize > maxSize ) return 0; // Все сообщение не влезит в буфер result[0] = startByte; result[1] = msg->messageType | ((u08)msg->isSecure << 7); result[2] = 0; // Пока 0 сообщение больше чем в одном пакете не предусмотерно u08 sz = sizeof(msg->deviceID)+msg->dataSize+CRC_SIZE; result[3] = sz; result[4] = (u08)(msg->deviceID & 0xFF); result[5] = (u08)(msg->deviceID >> 8); memCpy(result+6,msg->data,msg->dataSize); sz = 6+msg->dataSize; u16 c = crc16(sz,result); result[sz] = (u08)(c & 0xFF); result[sz+1] = (u08)(c >> 8); return sz+2; } u16 formFrame(const u16 maxSize, byte_ptr result, const message_t*const msg) { return formFrameBinary(maxSize,result,msg); } u16 parseFrame(const u16 sourceSize, const byte_ptr source, message_t* result) { return parseFrameBinary(sourceSize, source, result); }
C
#include <stdio.h> #include <stdlib.h> #define MIN(A, B) ((A > B)? B : A) #define MAX(A, B) ((A > B)? A : B) typedef struct tree { int k1,k2; struct tree *left,*mid,*right; }node,*node_pt; node_pt new() { node_pt temp=(node_pt)malloc(sizeof(node)); temp->left=temp->mid=temp->right=NULL; temp->k1=-999; temp->k2=-999; } node_pt searchTree (node_pt tree, int key) { if (tree == NULL) return NULL; if (key == tree->k1 || key == tree->k2) return tree; if (key < tree->k1) return searchTree(tree->left, key); else if (key > tree->k2) return searchTree(tree->right, key); return searchTree(tree->mid, key); } node_pt insertItem(node_pt tree,int item) { if (tree == NULL) { node_pt node = new(); node->k1 = item; return node; } if (tree->k1 == -999) { tree->k1 = item; return tree; } else if (tree->k2 == -999) { tree->k2 = MAX(item, tree->k1); tree->k1 = MIN(item, tree->k1); return tree; } else { if (item < tree->k1) { tree->left = insertItem(tree->left, item); } else if (item > tree->k2) { tree->right = insertItem(tree->right, item); } else { tree->mid = insertItem(tree->mid, item); } } if (tree->left == NULL && tree->mid == NULL && tree->right == NULL) { node_pt leftNode = new(); node_pt rightNode = new(); if (item < tree->k1) { leftNode->k1 = item; rightNode->k1 = tree->k2; } else if (item > tree->k2) { leftNode->k1 = tree->k1; tree->k1 = tree->k2; rightNode->k1 = item; } else { leftNode->k1 = tree->k1; tree->k1 = item; rightNode->k1 = tree->k2; } tree->k2 = -999; tree->left = leftNode; tree->mid = rightNode; return tree; } return tree; } void inorderTraversal (node_pt root) { if (root == NULL) return; inorderTraversal(root->left); if (root->k1 != -999) printf(" %d", root->k1); inorderTraversal(root->mid); if (root->k2 != -999) printf(" %d", root->k2); inorderTraversal(root->right); } int main (int argc, char const * argv []) { int x; printf("Enter elements one by one, -1 to break: "); node_pt tree = NULL; do { scanf(" %d", &x); if (x >= 0) tree = insertItem(tree, x); } while (x >= 0); printf("Inorder: \n"); inorderTraversal(tree); printf("\n\n"); return 0; }
C
//sa se afiseze palindroamele dintr-un interval [a,b] #include<stdio.h> #include<conio.h> int inv(int x) { int y = 0, z = x; while (x != 0) { y = y * 10 + x % 10; x = x / 10; } if (y == z) return 1; else return 0; } int main() { int n, a, b, aux; scanf("%d", &a); scanf("%d", &b); if (a > b) { aux = a; a = b; b = aux; } for (n = a; n <= b; n++) { if (inv(n) == 1) printf("%d ", n); } getch(); return 0; }
C
/** * @file semaforos.c * @author Lucia Asencio y Rodrigo de Pool * @date 31-3-2017 * @brief fichero que contiene la implementacion de la libreria de semaforos */ #include <sys/sem.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #include "../includes/semaforos.h" /** * Crea un nuevo semaforo con el key dado y del tamanio indicado. * Se inicializan los valores a 0 de todos los semaforos. * @param key clave para inicializar el semaforo * @param size cantidad de semaforos que se quieren * @param semid puntero a entero donde se guarda el identificador del array * de semaforos * @return devuelve un 0 si el semaforo ya estaba creado 1 si se ha creado. * Si se creo el semaforo en semid se guarda su Identificador * Si ya estaba creado y no hubo error se devuelve el identificador, en este caso * los valores del semaforo no son cambiados * Si no se logra crear el semafoto devuelve ERROR en semid */ int Crear_Semaforo(key_t key, int size, int *semid){ int i; union semun { int val; struct semid_ds *semstat; unsigned short *array; } arg; *semid = semget(key, size, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W); if (*semid == ERROR) { *semid = semget(key, size, SHM_R | SHM_W); if (*semid == ERROR) { return ERROR; } return 0; } /*En caso de que se este creando el semaforo se incializa la estructura*/ arg.array = (unsigned short *) malloc(sizeof(unsigned short) * size); for (i = 0; i < size; i++) arg.array[i] = 0; /*Se fijan valores a 0*/ semctl(*semid, size, SETALL, arg); free(arg.array); return 1; } /** * Iniciliaza el semaforo a los valores indicados * @param semid id del semaforo * @param array array de valores a asignar al semaforo * @return OK si no hubo errores, ERROR si los hubo */ int Inicializar_Semaforo(int semid, unsigned short *array){ union semun { int val; struct semid_ds *semstat; unsigned short *array; } arg; if (semid < 0 || array == NULL) return ERROR; arg.array = array; if (semctl(semid, 0, SETALL, arg) == -1) return ERROR; return OK; } /** * Borra un array de semaforos * @param semid identificador del array * @return devuelve OK si todo correcto, y ERROR en caso de error */ int Borrar_Semaforo(int semid){ if (semctl(semid, 0, IPC_RMID, 0) == -1) { return ERROR; } return OK; } /** * Funcion privada que nos sirve para generalizar el codigo de down y up * de un semaforo * El unico cambio es que op es -1 y si es down y 1 si es up. * Devuelve ERROR si hubo error o OK en caso de no haberlo */ int operacionSemaforo(int id, int num_sem, int undo, int op){ struct sembuf sem_oper; if (id < 0 || num_sem < 0 || (op != -1 && op != 1)) return ERROR; sem_oper.sem_num = num_sem; sem_oper.sem_op = op; sem_oper.sem_flg = undo; if (semop(id, &sem_oper, 1) == -1) return ERROR; return OK; } /** * Hace down a un semaforo * @param id identificador de array de semaforos * @param num_sem numero de semaforo dentro del array * @param undo flag que se quiere agregar (UNDO flag recomendable) * @return ERROR en caso de error, OK si todo correcto */ int Down_Semaforo(int id, int num_sem, int undo){ return operacionSemaforo(id, num_sem, undo, -1); } /** * Hace up a un semaforo * @param id identificador de array de semaforos * @param num_sem numero de semaforo dentro del array * @param undo flag que se quiere agregar (UNDO flag recomendable) * @return ERROR en caso de error, OK si todo correcto */ int Up_Semaforo(int id, int num_sem, int undo){ return operacionSemaforo(id, num_sem, undo, 1); } /** * Funcion privada que generaliza el comportamiento de DownMultiple_Semaforo y * UpMultiple_Semaforo. Se le pasa -1 si se quiere actuar como DownMultiple_Semaforo * y 1 si se quiere actuar como UpMultiple_Semaforo */ int operacionMultipleSemaforo(int id, int size, int undo, int *active, int op){ int i; if (size < 1) return ERROR; for (i = 0; i < size; i++) { if (operacionSemaforo(id, active[i], undo, op) == ERROR) return ERROR; } return OK; } /** * Hace down sobre un conjunto de semaforos. * @param id identificador del array de semaforos * @param size tamanio del array active * @param undo flag a agregarle a la operacion * @param active array con el conjunto de semaforos sobre el que se hace down * @return ERROR si hubo un error al hacer down en algun semaforo, OK * en caso de que todo fue correctamente */ int DownMultiple_Semaforo(int id, int size, int undo, int *active){ return operacionMultipleSemaforo(id, size, undo, active, -1); } /** * Hace up sobre un conjunto de semaforos. * @param id identificador del array de semaforos * @param size tamanio del array active * @param undo flag a agregarle a la operacion * @param active array con el conjunto de semaforos sobre el que se hace down * @return ERROR si hubo un error al hacer up en algun semaforo, OK * en caso de que todo fue correctamente */ int UpMultiple_Semaforo(int id, int size, int undo, int *active){ return operacionMultipleSemaforo(id, size, undo, active, 1); }
C
#include "cachelab.h" #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct node * Node; typedef struct deque * Deque; typedef unsigned long ul; int hit = 0, miss = 0, evict = 0; typedef struct node { ul tag; Node next; Node pre; } node; typedef struct deque { node sentinel; int size; int max; } deque; // Input Parsing: void loadArgs(int argc, char * argv[], int * s, int * e, int * b, int * len); int readline(char * buf, int * op, ul * address); // Deque Interface: void addFirst(Deque d, Node n); void removeLast(Deque d); // evict++; void delete(Deque d, Node n); void moveToFront(Deque d, Node n); Node search(Deque d, ul tag); // if NULL miss++ else hit++ then move n to front; // Cache Interface: void read(Deque cache, int b, int s, ul address); // void write(Deque cache, int b, int s, ul address); <- redundant int main(int argc, char * argv[]) { FILE * file; int s = 0, e = 0, b = 0, len = 0; // len = 2 ^ s; ul address = 0; int op = 0; char buf[64]; loadArgs(argc, argv, &s, &e, &b, &len); file = fopen(argv[argc - 1], "r"); Deque cache = (Deque)malloc(len * sizeof(deque)); for (int i = 0; i < len; ++i) cache[i].max = e; while (fgets(buf, 64, file) != NULL) { if (readline(buf, &op, &address) == 0) continue; if (op == 'L') { read(cache, b, s, address); } else if (op == 'S') { read(cache, b, s, address); } else { read(cache, b, s, address); read(cache, b, s, address); } } fclose(file); printSummary(hit, miss, evict); return 0; } // Input Parsing: void loadArgs(int argc, char * argv[], int * s, int * e, int * b, int * len) { int i = 1; for ( ; i < argc; ++i) { char * cur = argv[i]; if (strcmp(cur, "-s") == 0) *s = atoi(argv[++i]); else if (strcmp(cur, "-E") == 0) *e = atoi(argv[++i]); else if (strcmp(cur, "-b") == 0) *b = atoi(argv[++i]); } *len = 1 << *s; return; }; int readline(char * buf, int * op, ul * address) { if (buf[0] != ' ') return 0; *op = buf[1]; char * cur = &buf[3], * stop; int i = -1; while (cur[++i] != ','); cur[i] = '\0'; *address = strtoul(cur, &stop, 16); return 1; }; // Deque Interface: void addFirst(Deque d, Node n) { if (d->size == 0) { d->sentinel.next = n; n->pre = &(d->sentinel); n->next = &(d->sentinel); d->sentinel.pre = n; } else { Node front = d->sentinel.next; d->sentinel.next = n; n->pre = &(d->sentinel); n->next = front; front->pre = n; } ++d->size; return; }; void removeLast(Deque d) { Node last = d->sentinel.pre; delete(d, last); free(last); return; }; void delete(Deque d, Node n) { Node father = n->pre; Node son = n->next; father->next = son; son->pre = father; --d->size; return; } void moveToFront(Deque d, Node n) { delete(d, n); addFirst(d, n); return; } Node search(Deque d, ul tag) { if (d->size == 0) return NULL; Node start = d->sentinel.next; Node end = &(d->sentinel); while (start != end) { if (start->tag == tag) return start; start = start->next; } return NULL; }; // Cache Simulator: void read(Deque cache, int b, int s, ul address) { int num = (address >> b) & ((1 << s) - 1); ul tag = address >> (b + s); Deque d = &cache[num]; Node target = search(d, tag); if (target != NULL) { ++hit; moveToFront(d, target); } else { ++miss; Node n = (Node)malloc(sizeof(node)); n->tag = tag; if (d->size == d->max) { ++evict; removeLast(d); } addFirst(d, n); } return; };
C
/* ----- Comandos para Executar ----- gcc -o openMP -fopenmp openMP.c ./openMP */ #include <stdio.h> #include <stdlib.h> #include <time.h> // Mensurar tempo #include <unistd.h> // BIBLIOTECAS #include <termios.h> // PARA #include <fcntl.h> // KBHIT #include <omp.h> // OpenMP Library #define LENGTH 1500 // Maximo de produtos #define MAX_WEIGHT 10 // Peso maximo dos produtos int total_items; int sum_weights; int weights[LENGTH]; int previous_items; int input_array[LENGTH]; int input_generator() { int i = rand() % 5; if (i == 0){ return 1; }else{ return 0; } } int random_weight(){ int x = rand() % MAX_WEIGHT; // Caso gerar um valor igual a zero, retorna 1 // printf("\tPeso+: %d", x); if (x == 0) return 1; else return x; } int update_weights(int weights[]) { // Soma os pesos que estão armazenados no vetor for (int i = 0; i < LENGTH; i++) { sum_weights += weights[i]; } return sum_weights; } void update_display(int total_items, int sum_weights) { printf("\n\n-----L C D-----"); printf("\nNº de Itens: %d", total_items); printf("\nPeso Total: %d kg", sum_weights); } int main() { // Variaveis para calculo de tempo srand(time(NULL)); clock_t start, end; double cpu_time_used; weights[LENGTH] = 0; total_items = 0; previous_items = 0; #pragma omp parallel shared(total_items, previous_items, weights) num_threads(3) { printf("Thread %d iniciada.\n", omp_get_thread_num()); while (total_items < LENGTH) { if (input_generator) { #pragma omp critical // Bloqueia a variavel { total_items += 1; // Atualiza o numero de itens weights[total_items] = random_weight(); // Adiciona o peso do item no vetor } // Libera a variavel printf("\nThread %d ativada.\n", omp_get_thread_num()); // Atualiza display if (total_items != previous_items) { update_display(total_items, update_weights(weights)); previous_items = total_items; } } } } // Calcula o tempo para pesagem start = clock(); update_weights(weights); end = clock(); double weight_time = ((double)(end - start)) / CLOCKS_PER_SEC; // Calcula a taxa de atualização do display start = clock(); update_display(total_items, update_weights(weights)); end = clock(); double display_time = ((double)(end - start)) / CLOCKS_PER_SEC; // Fornece os tempos testados printf("\nTaxa de atualização: %f segundos", display_time); printf("\nTempo de contagem: %f segundos", weight_time*LENGTH); printf("\nTempo de pesagem: %f segundos\n", weight_time); }
C
#include "Module_Pile.h" #include "Labyrinthe.h" #include "Aleatoire.h" /************************************************************************************************/ /* DEFINITION */ /************************************************************************************************/ static int obtenir_prochaine_position(int chemin[],int longueur_chemin,int nb_lignes_grille,int nb_colonnes_grille) { srand(time(NULL)); //au pire on le laisse drette la int position_x = chemin[0] / nb_lignes_grille; int position_y = chemin[0] % nb_lignes_grille; int old_position_x = chemin[1] / nb_lignes_grille; int old_position_y = chemin[1] % nb_lignes_grille; int changement_y = 0, changement_x = 0; int nombre_a_renvoyer; if (longueur_chemin == 1) //si la poile est de 1 seul element { old_position_x = -1; //assigne les valeur precedente de x a des valeurs qui ne peuvent etre atteintes old_position_y = -1; } while ((!(changement_y == 0) && !(changement_x == 0)) || (changement_y == 0 && changement_x == 0) || ((old_position_x == position_x) && (old_position_y == position_y))) { do { position_x = chemin[0] / nb_lignes_grille; //reinitialise la position a sa valeur originale changement_x = (rand()%3)-1; //genere un NB random de -1, 0 ou 1 position_x += changement_x; //la position change de changement_x } while ((position_x < 0) || (position_x >= (nb_colonnes_grille))); do { position_y = chemin[0] % nb_lignes_grille; //reinitialise la position a sa valeur originale changement_y = (rand()%3)-1; //genere un NB random de -1, 0 ou 1 position_y += changement_y; //la position change de changement_x } while ((position_y < 0) || (position_y >= nb_lignes_grille)); } nombre_a_renvoyer = ((nb_lignes_grille*position_x) + position_y); return nombre_a_renvoyer; } void chemin_aleatoire_ajouter_un_pas(int* chemin[], int* longueur_chemin, int nb_lignes_grille, int nb_colonnes_grille) { int prochain_pas = 0; int position = 0; prochain_pas = obtenir_prochaine_position(*chemin, *longueur_chemin, nb_lignes_grille, nb_colonnes_grille); position = pile_est_present(*chemin, *longueur_chemin, prochain_pas); if(position > 0) { pile_tronquer(chemin, longueur_chemin, position); } else { pile_ajouter(chemin, longueur_chemin, prochain_pas); } }
C
#include <stdio.h> int map[10][10]; int arr[30]; int bingo; int checkG(){ for(int i=1; i<=5; i++){ int sum = 0; for(int j=1; j<=5; j++){ sum += map[i][j]; } if(sum == 0){ bingo++; } } } int checkS(){ for(int j=1; j<=5; j++){ int sum = 0; for(int i=1; i<=5; i++){ sum += map[i][j]; } if(sum == 0){ bingo++; } } } int checkD1(){ int sum = 0; for(int i=1; i<=5; i++){ sum += map[i][5-(i-1)]; } if(sum == 0){ bingo++; } } int checkD2(){ int sum = 0; for(int i=1; i<=5; i++){ sum += map[i][i]; } if(sum == 0){ bingo++; } } int main(){ for(int i=1; i<=5; i++){ for(int j=1; j<=5; j++){ scanf("%d", &map[i][j]); } } for(int i=1; i<=25; i++){ scanf("%d", &arr[i]); } for(int k=1; k<=25; k++){ for(int i=1; i<=5; i++){ for(int j=1; j<=5; j++){ if(arr[k] == map[i][j]){ map[i][j] = 0; bingo = 0; checkG(); checkS(); checkD1(); checkD2(); if(bingo >= 3){ printf("%d\n", k); return 0; } } } } } return 0; }
C
//Compilar no terminal usando: gcc MonteCarlo.c -o mc -lm -lgmp #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <gmp.h> void monteCarlo(int iterations); int main (){ srand(time(NULL)); int iterations = 1000000000; //numero de iterações monteCarlo(iterations); return 0; } void monteCarlo(int iterations){ //máx precisão mpf_set_default_prec(pow(10,5)); //variaveis mpf_t pts, ptsDentro, pi; //iniciando as variaveis int i; double x, y; mpf_init(pi); mpf_init(pts); mpf_init(ptsDentro); srand(time(NULL)); for(i = 0; i < iterations; i++){ x = ((double)rand()/(double)RAND_MAX); y = ((double)rand()/(double)RAND_MAX); //se x²+y² <= 1 //adiciona o ponto ao array de pontos dentro if(x*x + y*y <= 1){ mpf_add_ui(ptsDentro, ptsDentro, 1); } } //O número total de pontos é igual o de iterações //pi = 4*ptsDentro/pts mpf_mul_ui(ptsDentro, ptsDentro, 4); mpf_init_set_ui(pts, iterations); mpf_div(pi, ptsDentro, pts); gmp_printf("Monte Carlo : %.6Ff\n", pi); //limpando as variaveis mpf_clear(pi); mpf_clear(pts); mpf_clear(ptsDentro); }
C
/* Note:Your choice is C IDE */ int main() { int i,j,k,p,a[100][100],s[100]={0},m,n; scanf("%d",&k); for(p=1;p<=k;p++) { scanf("%d%d",&m,&n); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { scanf("%d",&a[i][j]); } } for(j=1;j<=n;j++) { s[p]=s[p]+(a[1][j]); } for(j=1;j<=n;j++) { s[p]=s[p]+(a[m][j]); } for(i=2;i<=m-1;i++) { s[p]=s[p]+a[i][1]+a[i][n]; } } printf("%d",s[1]); for(p=2;p<=k;p++) { printf("\n%d",s[p]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; } ; enum Boolean { false, true }; struct Node *sourceListRoot = NULL; struct Node *targetListRoot = NULL ; struct Node *tempListRoot = NULL ; void appendElementToSourceList( int value) ; void printSourceList() ; void makeSourceListPointToTheSecondNodeOfTempList(); void makeTempListFirstNodeConnectWithTargetListFirstNode(); void makeTargetListPointTempListFirstNode(); struct Node * getLastNode( struct Node *listRoot ) ; enum Boolean sourceListIsNotEmpty (); void printTargetList(); enum Boolean sourceListIsNotEmpty () { if ( sourceListRoot ) { return true; } return false; } void makeTargetListPointTempListFirstNode() { targetListRoot = tempListRoot; } void makeTempListFirstNodeConnectWithTargetListFirstNode() { if( ! tempListRoot ) { return; } tempListRoot->next = targetListRoot; } void makeSourceListPointToTheSecondNodeOfTempList() { if ( !tempListRoot ) { return; } sourceListRoot = tempListRoot->next; } void createSourceListWithTestData() { appendElementToSourceList( 100); appendElementToSourceList(200); appendElementToSourceList(300); appendElementToSourceList(400); appendElementToSourceList(500); } void printSourceList() { struct Node *currentNode = sourceListRoot; while( currentNode ) { printf("ListVal: %d\n", currentNode->data); currentNode = currentNode->next; } } void printTargetList () { struct Node *currentNode = targetListRoot; while( currentNode ) { printf("ListVal: %d\n", currentNode->data); currentNode = currentNode->next; } } struct Node * getLastNode( struct Node *listRoot ) { struct Node *currentNode = listRoot; if( !listRoot ) { printf("returning for null list\n"); return NULL; } while( currentNode->next ) { currentNode = currentNode->next; } return currentNode; } void appendElementToSourceList( int value) { struct Node *newNode = malloc(sizeof(struct Node) ); newNode->data = value; newNode->next = NULL; struct Node *lastNode = getLastNode(sourceListRoot); if ( lastNode ) { lastNode->next = newNode; } else { printf("Added New Node\n"); sourceListRoot = newNode; } } void makeTempListRootPointToSourceListRoot() { tempListRoot = sourceListRoot; } void main (int argc, const char * argv[]) { createSourceListWithTestData(); printf("Lets see how the source list look like in the beginning\n"); printSourceList(); while ( sourceListIsNotEmpty() ) { // Step 1 makeTempListRootPointToSourceListRoot( ); // Step 2 makeSourceListPointToTheSecondNodeOfTempList(); // Step 3 makeTempListFirstNodeConnectWithTargetListFirstNode(); // Step 4 makeTargetListPointTempListFirstNode(); // examine the source list again // printf("Lets see how the source list look like now\n"); // printSourceList(); } // examine the source list again printf("Lets see how the target list look like now\n"); printTargetList(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_float.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oandrosh <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/28 16:55:20 by oandrosh #+# #+# */ /* Updated: 2019/01/28 18:23:07 by oandrosh ### ########.fr */ /* */ /* ************************************************************************** */ #include "../ft_printf.h" static void minus(long double ldb, int *flags, int size) { if (ldb < 0) { ft_joinchar('-', 1); ldb *= -1; } else if (flags[1] == 1) ft_joinchar('+', 1); else if (flags[2] == 1) ft_joinchar(' ', 1); else flags[6]++; ft_joinstr(ft_ftoa(ldb, flags[7])); if (flags[3] == 1 && flags[7] == 0) ft_joinchar('.', 1); if (--flags[6] > size) ft_joinchar(' ', (flags[6] - size)); } static void not_minus(long double ldb, int *flags, int size) { if (flags[1] == 1 || flags[2] == 1 || ldb < 0) flags[6]--; if (size < flags[6] && flags[4] != 1) ft_joinchar(' ', (flags[6] - size)); if (ldb < 0) { ft_joinchar('-', 1); ldb *= -1; } else if (flags[1] == 1) ft_joinchar('+', 1); else if (flags[2] == 1) ft_joinchar(' ', 1); if (size < flags[6] && flags[4] == 1) ft_joinchar('0', (flags[6] - size)); ft_joinstr(ft_ftoa(ldb, flags[7])); if (flags[3] == 1 && flags[7] == 0) ft_joinchar('.', 1); } static void add_flags(long double ldb, int *flags) { int length; length = ft_defsize_float(ldb, flags[7]); if (flags[0] == 1) minus(ldb, flags, length); else not_minus(ldb, flags, length); } void ft_float(int *flags, va_list ap) { long double flt; if (flags[7] < 0) flags[7] = 6; if (flags[7] == 0 && flags[3] == 1) flags[6]--; if (flags[5] == 5) { flt = va_arg(ap, long double); add_flags(flt, flags); } else { flt = va_arg(ap, double); add_flags(flt, flags); } }
C
#include <stdbool.h> #include "dictionary.h" #include <stdio.h> #include <cs50.h> #include <math.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <strings.h> unsigned int numWords = 0; // Represents a node in a hash table typedef struct node { char word[LENGTH + 1]; struct node *next; } node; // Number of buckets in hash table const unsigned int N = 65536; // Hash table node *table[N]; // Returns true if word is in dictionary else false bool check(const char *word) { unsigned int bucket = hash(word); node *tmp = table[bucket]; while(tmp != NULL) { if (strcasecmp(word, tmp->word) == 0) { return true; } tmp = tmp->next; } return false; } // Hashes word to a number unsigned int hash(const char *word) { unsigned int hash = 0; // char *lword = malloc(sizeof(*word) + 1); char lword[sizeof(*word)]; for (int a = 0; a < strlen(word); a++) { lword[a] = (char) tolower(word[a]); } for (int i = 0; i < 3; i++) { if (i < strlen(word)) { hash = hash + (int) lword[i]; } } // free(lword); return hash; } // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { node *n; FILE * file = fopen(dictionary, "r"); if (file == NULL) { return false; } char indWord[LENGTH + 1]; while (fscanf(file, "%s", indWord) != EOF) { n = malloc(sizeof(node)); if (n == NULL) { return false; } numWords++; strcpy(n->word, indWord); n->next = table[hash(n->word)]; table[hash(n->word)] = n; } return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { return numWords; } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { node *cursor = NULL; node *tmp = NULL; for (int i = 0; i < N; i++) { cursor = table[i]; while (tmp != NULL) { tmp = cursor->next; free(cursor); cursor = tmp; } } return true; }
C
#include "libmx.h" void mx_str_reverse(char *s) { int first = 0; int last; if (!s) return; last = mx_strlen(s) - 1; while(first < last && s) { mx_swap_char(&s[first], &s[last]); first++; last--; } }
C
/* ** EPITECH PROJECT, 2021 ** diogo le dog ** File description: ** wouf wouf */ #include "../include/shell.h" #include "../include/my_termios.h" #include "../include/my.h" char *remove_parenthesis(char *str) { char new[255] = {0}; int index = 0; for (int i = 0; str[i]; i++) { if (str[i] != '(' && str[i] != ')') { new[index] = str[i]; index++; } } return (strdup(new)); } bool is_number(char *str) { int neg_nb = 0; for (int i = 0; str[i]; i++) { if (str[i] < '0' || str[i] > '9') return (false); if (str[i] == '-') neg_nb++; } if (neg_nb > 1) return (false); return (true); } int verif_equal_statement(char **tab, char **env, int *pip, sh_t *sh) { if ((is_number(tab[1]) && !is_number(tab[3])) || (!is_number(tab[1]) && is_number(tab[3]))) return (0); if (is_number(tab[1])) { if (atoi(tab[1]) == atoi(tab[3])) { return (run(tabcat(tab + 4), env, pip, sh)); } } if (strcmp(tab[1], tab[3]) == 0) { return (run(tabcat(tab + 4), env, pip, sh)); } return (0); } int verif_not_equal_statement(char **tab, char **env, int *pip, sh_t *sh) { if ((is_number(tab[1]) && !is_number(tab[3])) || (!is_number(tab[1]) && is_number(tab[3]))) return (0); if (is_number(tab[1])) { if (atoi(tab[1]) != atoi(tab[3])) { return (run(tabcat(tab + 4), env, pip, sh)); } } if (strcmp(tab[1], tab[3]) != 0) return (run(tabcat(tab + 4), env, pip, sh)); return (0); } int exec_if(char **tab, char **env, int *pip, sh_t *sh) { if (get_arr_size(tab) <= 4 || (!strcmp(tab[2], "==") && !strcmp(tab[2], "!="))) return (0); tab[1] = remove_parenthesis(tab[1]); tab[3] = remove_parenthesis(tab[3]); if (tab[2][0] == '=') return (verif_equal_statement(tab, env, pip, sh)); return (verif_not_equal_statement(tab, env, pip, sh)); }
C
#include <stdio.h> // print ever character on a new line main() { char c; while((c = getchar()) != EOF) printf("%d",c); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <time.h> #define SIZE 8192 #define PORT_NO 12345 int main() { int server_sockfd, client_sockfd; struct sockaddr_in server_address, client_address; int client_len; int fd_size, ret; int optval; char buf[SIZE]; fd_set readfds, testfds; FILE *log_file; log_file = fopen("telnet_ip.log", "a"); if (log_file == NULL) { perror("fopen()"); exit(1); } server_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (server_sockfd < 0) { perror("socket()"); exit(1); } optval = 1; if (setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) { perror("setsockopt()"); exit(1); } server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(PORT_NO); if (bind(server_sockfd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) { perror("bind()"); exit(1); } if (listen(server_sockfd, 5) < 0) { perror("listen()"); exit(1); } fd_size = server_sockfd + 1; FD_ZERO(&readfds); FD_SET(server_sockfd, &readfds); while(1) { testfds = readfds; ret = select(fd_size, &testfds, 0, 0, 0); if (ret < 0) { perror("select()"); exit(1); } if (ret == 0) continue; if (FD_ISSET(server_sockfd, &testfds)) { client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); if (client_sockfd < 0) { perror("accept()"); exit(1); } time_t t = time(0); struct tm *tm = localtime(&t); char *ip_addr; ip_addr = (char *)inet_ntoa(client_address.sin_addr); fprintf(log_file, "%d-%02d-%02d %02d:%02d:%02d %s\n", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, ip_addr); fflush(log_file); sprintf(buf, "Your IP address is %s\n", ip_addr); write(client_sockfd, buf, strlen(buf)); close(client_sockfd); } } return 0; }
C
// // main.c // mini_project_1_v2 // // Created by engine210 on 2019/4/7. // Copyright © 2019 engine210. All rights reserved. // #include "lex.h" /* the only type: integer everything is an expression statement := END | expr END expr := term expr_tail expr_tail := ADDSUB term expr_tail | NIL term := factor term_tail term_tail := MULDIV factor term_tail | NIL factor := INT | ADDSUB INT | ADDSUB ID | ID ASSIGN expr | ID | LPAREN expr RPAREN */ Symbol table[TBLSIZE]; int sbcount = 0; int reg_available[8]; //indicate r0~r7 is available or not void statement(void); BTNode* bit_or(void); BTNode* bit_xor(void); BTNode* bit_and(void); BTNode* expr(void); BTNode* term(void); BTNode* factor(void); BTNode* makeNode(TokenSet, const char*); int getval(void); int setval(char*, int); void freeTree(BTNode*); void printPrefix(BTNode*); int evaluateTree(BTNode*); void error(ErrorType errorNum); int printAssemble(BTNode* root); void table_init(void); int flag = 0; int firstID; int main(int argc, char* argv[]) { char c; int i; //freopen("input.txt", "r", stdin); table_init(); while (scanf("%c", &c) != EOF) { ungetc(c, stdin); firstID = 1; for (i = 0; i < 8; i++) reg_available[i] = 1; statement(); if (flag) { printf("EXIT 1\n"); break; } } if (!flag) { printf("MOV r0 [0]\n"); printf("MOV r1 [4]\n"); printf("MOV r2 [8]\n"); printf("EXIT 0\n"); } return 0; } void table_init() { //set x, y, z to table table[0].name[0] = 'x'; table[0].name[1] = '\0'; table[0].val = 0; table[1].name[0] = 'y'; table[1].name[1] = '\0'; table[1].val = 0; table[2].name[0] = 'z'; table[2].name[1] = '\0'; table[2].val = 0; sbcount = 3; } void statement(void) { BTNode* retp; if (match(END)) { //printf(">> "); advance(); } else { retp = bit_or(); if (match(END)) { if (retp->token != ASSIGN || retp->left->token != ID) { flag = 1; } if (!flag) { printAssemble(retp); } freeTree(retp); advance(); } } } BTNode* bit_or() { BTNode *retp, *left; retp = left = bit_xor(); while (match(OR)) { // tail recursion => while retp = makeNode(OR, getLexeme()); advance(); retp->right = bit_xor(); retp->left = left; left = retp; } return retp; } BTNode* bit_xor() { BTNode *retp, *left; retp = left = bit_and(); while (match(XOR)) { // tail recursion => while retp = makeNode(XOR, getLexeme()); advance(); retp->right = bit_and(); retp->left = left; left = retp; } return retp; } BTNode* bit_and() { BTNode *retp, *left; retp = left = expr(); while (match(AND)) { // tail recursion => while retp = makeNode(AND, getLexeme()); advance(); retp->right = expr(); retp->left = left; left = retp; } return retp; } // expr := term expr_tail // expr_tail := ADDSUB term expr_tail | NIL BTNode* expr(void) { BTNode *retp, *left; retp = left = term(); while (match(ADDSUB)) { // tail recursion => while retp = makeNode(ADDSUB, getLexeme()); advance(); retp->right = term(); retp->left = left; left = retp; } return retp; } // term := factor term_tail // term_tail := MULDIV factor term_tail | NIL BTNode* term(void) { BTNode *retp, *left; retp = left = factor(); while (match(MULDIV)) { // tail recursion => while retp = makeNode(MULDIV, getLexeme()); advance(); retp->right = factor(); retp->left = left; left = retp; } return retp; } BTNode* factor(void) { BTNode* retp = NULL; char tmpstr[MAXLEN]; if (match(INT)) { retp = makeNode(INT, getLexeme()); retp->val = getval(); advance(); } else if (match(ID)) { BTNode* left = makeNode(ID, getLexeme()); left->val = getval(); firstID = 0; strcpy(tmpstr, getLexeme()); advance(); if (match(ASSIGN)) { retp = makeNode(ASSIGN, getLexeme()); advance(); retp->right = bit_or(); retp->left = left; } else { retp = left; } } else if (match(ADDSUB)) { strcpy(tmpstr, getLexeme()); advance(); if (match(ID) || match(INT)) { retp = makeNode(ADDSUB, tmpstr); if (match(ID)) { retp->right = makeNode(ID, getLexeme()); } else { retp->right = makeNode(INT, getLexeme()); } retp->right->val = getval(); retp->left = makeNode(INT, "0"); retp->left->val = 0; advance(); } else { error(NOTNUMID); } } else if (match(LPAREN)) { advance(); retp = bit_and(); if (match(RPAREN)) { advance(); } else { error(MISPAREN); } } else { error(NOTNUMID); } return retp; } /* create a node without any child */ BTNode* makeNode(TokenSet tok, const char *lexe) { BTNode *node = (BTNode*) malloc(sizeof(BTNode)); strcpy(node->lexeme, lexe); node->token= tok; node->val = 0; node->left = NULL; node->right = NULL; return node; } /* clean a tree */ void freeTree(BTNode *root) { if (root!=NULL) { freeTree(root->left); freeTree(root->right); free(root); } } /* print a tree by pre-order */ void printPrefix(BTNode *root) { if (root != NULL) { printf("%s ", root->lexeme); printPrefix(root->left); printPrefix(root->right); } } /* traverse the syntax tree by pre-order and evaluate the underlying expression */ int evaluateTree(BTNode *root) { int retval = 0, lv, rv; if (root != NULL) { switch (root->token) { case ID: case INT: retval = root->val; break; case OR: case XOR: case AND: case ASSIGN: case ADDSUB: case MULDIV: lv = evaluateTree(root->left); rv = evaluateTree(root->right); if (strcmp(root->lexeme, "|") == 0) { retval = lv | rv; } else if (strcmp(root->lexeme, "^") == 0) { retval = lv ^ rv; } else if (strcmp(root->lexeme, "&") == 0) { retval = lv & rv; } else if (strcmp(root->lexeme, "+") == 0) { retval = lv + rv; } else if (strcmp(root->lexeme, "-") == 0) { retval = lv - rv; } else if (strcmp(root->lexeme, "*") == 0) { retval = lv * rv; } else if (strcmp(root->lexeme, "/") == 0) { if (rv == 0) { error(NAN); } else { retval = lv / rv; } } else if (strcmp(root->lexeme, "=") == 0) { retval = setval(root->left->lexeme, rv); } break; default: retval = 0; } } return retval; } /*get the value of the token, if the token is an interger, then return it's value if the token is an ID, then return it's value, or add this ID to table */ int getval(void) { int i, retval = 0, found; if (match(INT)) { retval = atoi(getLexeme()); } else if (match(ID)) { i = 0; found = 0; retval = 0; while (i<sbcount && !found) { if (strcmp(getLexeme(), table[i].name) == 0) { retval = table[i].val; found = 1; break; } else { i++; } } if (!found) { if (!firstID) { flag = 1; } if (sbcount < TBLSIZE) { strcpy(table[sbcount].name, getLexeme()); table[sbcount].val = 0; sbcount++; } else { error(RUNOUT); } } } return retval; } int setval(char *str, int val) { int i, retval = 0; i = 0; while (i < sbcount) { if (strcmp(str, table[i].name) == 0) { table[i].val = val; retval = val; break; } else { i++; } } return retval; } void error(ErrorType errorNum) { /* switch (errorNum) { case MISPAREN: fprintf(stderr, "Mismatched parenthesis\n"); break; case NOTNUMID: fprintf(stderr, "Number or identifier expected\n"); break; case NOTFOUND: fprintf(stderr, "%s not defined\n", getLexeme()); break; case RUNOUT: fprintf(stderr, "Out of memory\n"); break; case NAN: fprintf(stderr, "Not a number\n"); } */ flag = 1; } int printAssemble(BTNode* root) { char c = root->lexeme[0]; int reg1, reg2, i, j; if (isdigit(c)) { for (i = 0; i < 8; i++) { if (reg_available[i]) break; } reg_available[i] = 0; printf("MOV r%d %d\n", i, root->val); return i; } else if (c == '|') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("OR r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '^') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("XOR r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '&') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("AND r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '+') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("ADD r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '-') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("SUB r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '*') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("MUL r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '/') { reg1 = printAssemble(root->left); reg2 = printAssemble(root->right); printf("DIV r%d r%d\n", reg1, reg2); reg_available[reg2] = 1; return reg1; } else if (c == '=') { for (i = 0; i < sbcount; i++) { if (strcmp(root->left->lexeme, table[i].name) == 0) { break; } } reg2 = printAssemble(root->right); printf("MOV [%d] r%d\n", i*4, reg2); } else if (isalpha(c) || c == '_') { for (i = 0; i < 8; i++) { if (reg_available[i]) break; } reg_available[i] = 0; for (j = 0; j < sbcount; j++) { if (strcmp(root->lexeme, table[j].name) == 0) { break; } } printf("MOV r%d [%d]\n", i, j*4); return i; } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "long_math.h" #include "stack.h" int comparator(Bignumber *f, Bignumber *s) { //if ((list_len(f)) > (list_len(s))) return 1; if(f->size > s -> size) return 1; //else if ((list_len(f)) < (list_len(s))) return -1; else if(f->size < s -> size) return -1; else { Node *f1 = f->tail; Node *s1 = s -> tail; while(f1) { if((f1->digit) > (s1 -> digit)) { return 1; } else if ((f1->digit) < (s1 -> digit)) { return -1; } else { f1 = f1 -> prev_node; s1 = s1 -> prev_node; } } return 0; } } void eliminate_zeroes(Bignumber **res) { Node *tmp; while(((*res)->tail !=NULL) && ((*res)->tail->digit == 0)&&((*res)->head->next_node)) { tmp = (*res)->tail; (*res)->tail = (*res) ->tail ->prev_node; (*res) ->tail ->next_node = NULL; free(tmp); (*res)->size--; } } void sum_of(Stack **stack) { char sign = ((*stack)->next_number->sign == 0) ? 0:1; Bignumber *first = pop(stack); Bignumber *second = pop(stack); Node *f = first -> head, *s = second -> head; Bignumber *res = new_Number(); char carry = 0, sum = 0; while(f != NULL || s != NULL) { sum = carry + (f? f->digit: 0) + (s? s->digit: 0); carry = sum / 10;//(sum >= 10)? 1 : 0; // or carry = sum / 10; sum = sum % 10; add_to_e(&res,sum); if(f) free_node(&f);//f = f -> next_node; if(s) free_node(&s);//s = s -> next_node; } if(carry > 0) { add_to_e(&res, carry); } free(first); free(second); push(stack, res); (*stack) -> sign = sign; } Bignumber *sum_factors(Bignumber **first, Bignumber **second) { //Bignumber *first_to_free = (*first), *second_to_free = (*second); Node *f = (*first) -> head, *s = (*second) ->head; Bignumber *res = new_Number(); //Bignumber *tmp, *prev = NULL; char carry = 0, sum; while(f != NULL || s != NULL) { sum = carry + (f? f->digit: 0) + (s? s->digit: 0); carry = (sum >= 10)? 1 : 0; sum = sum % 10; add_to_e(&res,sum); if(f) free_node(&f); if(s) free_node(&s); } if(carry > 0) { add_to_e(&res, carry); } free(*first); free(*second); return res; } void multiply_of(Stack **stack) { char s2 = (*stack) -> sign; char s1 = (*stack)->next_number->sign; Bignumber *first = pop(stack); Bignumber *second = pop(stack); Bignumber *res = new_Number(); if((first->tail->digit == 0)||(second->tail->digit == 0)) { add_to_e(&res,0); push(stack,res); (*stack) -> sign = 0; free_list(first); free_list(second); return; } Node *f = first ->head; Node *s = second -> head; add_to_e(&res, 0); char factor; int n = 0; Node *tmp = NULL; while(s) { int carry = 0; Bignumber *tmp_res = new_Number(); tmp = f; while(tmp) { factor = ((s -> digit)*(tmp ->digit)) + carry; add_to_e(&tmp_res,factor % 10); carry = factor / 10; if(!s->next_node) free_node(&tmp); else tmp = tmp -> next_node; } if(carry > 0) add_to_e(&tmp_res, carry); int i; for(i = 0; i < n; i++) { add_to_b(&tmp_res,0); } res = sum_factors(&res, &tmp_res); n++; s = s -> next_node; } push(stack, res); (*stack) -> sign = (s1 == s2) ? 0:1; free(first); free_list(second); } void substraction(Stack **stack) { Bignumber *res = new_Number(); char s_res = (*stack)->next_number->sign; Bignumber *second = pop(stack); Bignumber *first = pop(stack); if(comparator(first, second) == 0) { free_list(first); free_list(second); add_to_e(&res, 0); push(stack, res); (*stack) -> sign = 0; return; } if(comparator(first,second) == -1) { s_res = (s_res == 1) ? 0:1; swap(&first, &second); } int n,m; if((n =first -> size) != (m = second -> size)) { int i; for(i = 0; i < n-m; i++) add_to_e(&second, 0); } Node *f = first->head, *s = second->head; char carry = 0,sub; while(f && s) { sub = ((f->digit) - (s->digit)) + carry; if(sub < 0) { sub += 10; carry = -1; } else { carry = 0; } add_to_e(&res, sub); free_node(&f); free_node(&s); } free(first); free(second); eliminate_zeroes(&res); push(stack, res); (*stack) -> sign = s_res; } Bignumber *division_sub(Bignumber **f, Bignumber **s) { Bignumber *res = new_Number(); Bignumber *first = *f; Bignumber *second = *s; if(comparator(first, second) == 0) { free_list(*f); free_list(*s); add_to_e(&res, 0); return res; } int n,m; if((n =first -> size) != (m = second -> size)) { int i; for(i = 0; i < n-m; i++) add_to_e(&second, 0); } Node *fp = first->head, *sp = second->head; char carry = 0,sub; while(fp && sp) { sub = ((fp->digit) - (sp->digit)) + carry; if(sub < 0) { sub += 10; carry = -1; } else { carry = 0; } add_to_e(&res, sub); free_node(&fp); free_node(&sp); } free(first); free(second); eliminate_zeroes(&res); return res; } Bignumber *division_multiply(Bignumber **first, char i) { Bignumber *res = new_Number(); Node *f = (*first)->head; char factor; char carry = 0; while(f) { factor = (f -> digit) * i + carry; add_to_e(&res,(factor %10)); carry = factor / 10; f = f -> next_node; } if(carry > 0) add_to_e(&res, carry); return res; } void division(Stack **stack) { char s2 = (*stack) -> sign; char s1 = (*stack)->next_number->sign; Bignumber *res = new_Number(); Bignumber *second = pop(stack); Bignumber *first = pop(stack); if(second ->tail->digit == 0) { free_list(first); free_list(second); printf("Division by 0"); exit(1); } if(comparator(first, second)== -1) { free_list(first); free_list(second); add_to_e(&res, 0); push(stack,res); return; } Bignumber *tmp = new_Number(); Node *fpointer = first->tail; add_to_b(&tmp, fpointer -> digit); while(comparator(tmp, second) == -1) { fpointer = fpointer -> prev_node; add_to_b(&tmp, fpointer -> digit); } char i = 1; int comp; Bignumber *tmp_res = division_multiply(&second, i); while(((comp = comparator(tmp_res,tmp)) == -1) || (comp == 0)) { i++; free_list(tmp_res); tmp_res = division_multiply(&second, i); } free_list(tmp_res); i -=1; tmp_res = division_multiply(&second, i); add_to_e(&res, i); tmp = division_sub(&tmp, &tmp_res); fpointer = fpointer -> prev_node; while(fpointer) { while(fpointer) { add_to_b(&tmp, fpointer->digit); eliminate_zeroes(&tmp); if(comparator(tmp, second) == -1) { add_to_b(&res, 0); fpointer = fpointer->prev_node; eliminate_zeroes(&tmp); } else { fpointer = fpointer -> prev_node; //eliminate_zeroes(&tmp); break; } } i = 1; tmp_res = division_multiply(&second, i); while(((comp = comparator(tmp_res,tmp)) == -1) || (comp == 0)) { i++; free_list(tmp_res); tmp_res = division_multiply(&second, i); } i -=1; free_list(tmp_res); if (i != 0) { tmp_res = division_multiply(&second, i); add_to_b(&res, i); tmp = division_sub(&tmp, &tmp_res); } } free_list(tmp); free_list(first); free_list(second); push(stack,res); (*stack) -> sign = (s1 == s2) ? 0:1; }
C
#include "mish_core.h" static uint64_t rng_state[4]; static mutator_mode mut_mode; static insn_candidate insn_cand; /* An x86 instruction can have up to 4 legacy prefixes, * in any order, with no more than 1 prefix from each group. */ static uint8_t legacy_prefixes[] = { // Prefix group 1. 0xf0, // repeat/lock 0xf3, // rep, repe 0xf2, // repne // Prefix group 2. 0x2e, // segment override, cs 0x36, // segment override, ss 0x3e, // segment override, ds 0x26, // segment override, es 0x64, // segment override, fs 0x65, // segment override, gs // Prefix group 3. 0x66, // operand size override // Prefix group 4. 0x67, // address size override }; /* REX prefixes apply in long (64-bit) mode, and are made up * of a fixed 4-bit pattern + extension bits for operand size, * ModR/M and SIB. * * Each instruction should only have one REX prefix. */ static uint8_t rex_prefixes[] = { 0b01000000, // ---- 0b01000001, // ---B 0b01000010, // --X- 0b01000011, // --BX 0b01000100, // -R-- 0b01000101, // -R-B 0b01000110, // -RX- 0b01000111, // -RXB 0b01001000, // W--- 0b01001001, // W--B 0b01001010, // W-X- 0b01001011, // W-XB 0b01001100, // WR-- 0b01001101, // WR-B 0b01001110, // WRX- 0b01001111, // WRXB }; #ifndef NO_XOROSHIRO_RNG static inline uint64_t xoroshiro256_rotl(const uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } uint64_t xoroshiro256_next(void) { const uint64_t result_starstar = xoroshiro256_rotl(rng_state[1] * 5, 7) * 9; const uint64_t t = rng_state[1] << 17; rng_state[2] ^= rng_state[0]; rng_state[3] ^= rng_state[1]; rng_state[1] ^= rng_state[2]; rng_state[0] ^= rng_state[3]; rng_state[2] ^= t; rng_state[3] = xoroshiro256_rotl(rng_state[3], 45); return result_starstar; } static inline uint64_t rand_long() { return xoroshiro256_next(); } static inline uint8_t rand_byte() { return (uint8_t)rand_long(); } #else static uint64_t rand_long() { uint64_t it; mish_getrandom(&it, sizeof(it), 0); return it; } static uint8_t rand_byte() { uint8_t it; mish_getrandom(&it, sizeof(it), 0); return it; } #endif /* Creates a random (potentially invalid) opcode. * Opcodes are 1-3 bytes long, and come in three formats: * 1. Single byte (raw opcode) * 2. Two bytes (escape byte, opcode) * 3. Three bytes (escape byte 1, escape byte 2, opcode) */ static void rand_opcode(opcode *opc) { switch (rand_byte() % 4) { case 0: { opc->len = 1; opc->op[0] = rand_byte(); break; } case 1: { opc->len = 2; opc->op[0] = 0x0f; opc->op[1] = rand_byte(); break; } case 2: { opc->len = 3; opc->op[0] = 0x0f; opc->op[1] = 0x38; opc->op[2] = rand_byte(); break; } case 3: { opc->len = 3; opc->op[0] = 0x0f; opc->op[1] = 0x3a; opc->op[2] = rand_byte(); break; } } } static void build_sliding_candidate() { memset(&insn_cand, 0, sizeof(insn_candidate)); /* 4 random legacy prefixes. * * Observe that we don't attempt to enforce the "1 prefix from each group" rule. */ for (int i = 0; i < 4; ++i) { insn_cand.insn[i] = legacy_prefixes[rand_byte() % sizeof(legacy_prefixes)]; } insn_cand.len += 4; /* REX prefix choices: * 0. Random prefix from rex_prefixes table * 1. Completely randomized prefix * 3. No REX prefix */ switch (rand_byte() % 3) { case 0: { insn_cand.insn[insn_cand.len] = rex_prefixes[rand_byte() % sizeof(rex_prefixes)]; insn_cand.len++; break; } case 1: { insn_cand.insn[insn_cand.len] = rand_byte(); insn_cand.len++; break; } case 2: { break; } } /* Opcode, up to 3 bytes. */ opcode opc; rand_opcode(&opc); memcpy(insn_cand.insn + insn_cand.len, opc.op, opc.len); insn_cand.len += opc.len; /* ModR/M and SIB. For now, just two random bytes. */ insn_cand.insn[insn_cand.len++] = rand_byte(); insn_cand.insn[insn_cand.len++] = rand_byte(); /* Displacement. Either none, or 1, 2, 4, or 8 bytes. */ if (rand_byte() % 2 == 0) { uint8_t displen = 1 << (rand_byte() % 4); uint64_t disp = rand_long(); memcpy(insn_cand.insn + insn_cand.len, &disp, displen); insn_cand.len += displen; } /* Immediate. Either none, or 1, 2, 4, or 8 bytes. */ if (rand_byte() % 2 == 0) { uint8_t immlen = 1 << (rand_byte() % 4); uint64_t imm = rand_long(); memcpy(insn_cand.insn + insn_cand.len, &imm, immlen); insn_cand.len += immlen; } } /* Havoc: generate a random instruction candidate. */ static bool havoc_candidate(input_slot *slot) { slot->len = (rand_byte() % MISHEGOS_INSN_MAXLEN) + 1; uint64_t lower = rand_long(); uint64_t upper = rand_long(); memcpy(slot->raw_insn, &lower, 8); memcpy(slot->raw_insn + 8, &upper, 7); return true; } /* Sliding: generate an instruction candidate with the * "sliding" approach. */ static bool sliding_candidate(input_slot *slot) { /* An offset of zero into our sliding candidate indicates that we've slid * all the way through and need to build a new candidate. */ if (insn_cand.off == 0) { build_sliding_candidate(); } /* If our sliding candidate is less than the maximum instruction size, * then we have nothing to slide. Just copy it try a new candidate on the next * call. * * Otherwise, take the maximum instruction size from our sliding * candidate, plus the current offset. This gives us a bunch of * high quality instruction "windows". */ if (insn_cand.len <= MISHEGOS_INSN_MAXLEN) { memcpy(slot->raw_insn, insn_cand.insn, insn_cand.len); slot->len = insn_cand.len; insn_cand.off = 0; // Shouldn't be necessary, but just to be explicit. } else { memcpy(slot->raw_insn, insn_cand.insn + insn_cand.off, MISHEGOS_INSN_MAXLEN); slot->len = MISHEGOS_INSN_MAXLEN; insn_cand.off = (insn_cand.off + 1) % (insn_cand.len - MISHEGOS_INSN_MAXLEN + 1); } return true; } /* Structured: generate an instruction candidate with the * "structured" approach. */ static bool structured_candidate(input_slot *slot) { /* We mirror build_sliding_candidate here, but with the constraint that * we never overapproximate: we constrain ourselves to trying * to build something that looks like an instruction of no more * than 15 bytes. */ uint8_t len = 0; /* Up to 4 legacy prefixes. Like sliding, we don't try to enforce group rules. * Unlike sliding, we allow for the possibility of no legacy prefixes. * Running max: 4. */ uint8_t prefix_count = (rand_byte() % 5); for (int i = 0; i < prefix_count; ++i) { slot->raw_insn[i] = legacy_prefixes[rand_byte() % sizeof(legacy_prefixes)]; } len = prefix_count; /* One or none REX prefixes. * Always choose a valid REX prefix if we're inserting one. * Running max: 5. */ if (rand_byte() % 2) { slot->raw_insn[len] = rex_prefixes[rand_byte() % sizeof(rex_prefixes)]; len++; } /* Random (but structured) opcode. Same as sliding. * Running max: 8 */ opcode opc; rand_opcode(&opc); memcpy(slot->raw_insn + len, opc.op, opc.len); len += opc.len; /* One or none ModR/M bytes, and one or none SIB bytes. * Both of these are just 8-bit LUTs, so they can be fully random. * Running max: 10. */ if (rand_byte() % 2) { slot->raw_insn[len] = rand_byte(); len++; } if (rand_byte() % 2) { slot->raw_insn[len] = rand_byte(); len++; } /* Finally, we have up to 5 bytes to play with for the immediate and * displacement. Fill some amount of that (maybe not all) with randomness. */ uint64_t tail = rand_long(); uint8_t tail_size = rand_byte() % 6; memcpy(slot->raw_insn + len, &tail, tail_size); len += tail_size; slot->len = len; return true; } /* Dummy: Generates a single NOP for debugging purposes. */ static bool dummy_candidate(input_slot *slot) { slot->raw_insn[0] = 0x90; slot->len = 1; /* NOTE(ww): We only ever want to fill one input slot with our dummy candidate, * since other parts of mishegos disambiguate worker outputs by keying on the input. */ return false; } /* Manual: reads instruction candidates from stdin, one per line. * Candidates are expected to be in hex format, with no 0x or \x prefix. */ static bool manual_candidate(input_slot *slot) { char *line = NULL; size_t size; if (getline(&line, &size, stdin) < 0) { /* Input exhausted. */ return false; } line[strcspn(line, "\n")] = '\0'; size_t linelen = strlen(line); if (linelen == 0 || linelen > MISHEGOS_INSN_MAXLEN * 2) { return false; } hex2bytes(slot->raw_insn, line, linelen); slot->len = linelen / 2; return true; } void mutator_init() { DLOG("initializing the mutation engine"); memcpy(rng_state, GET_CONFIG()->rng_seed, sizeof(rng_state)); DLOG("rng seed:"); hexputs((uint8_t *)rng_state, sizeof(rng_state)); mut_mode = GET_CONFIG()->mut_mode; } /* Generate a single fuzzing candidate and populate the given input slot with it. * Returns false if the configured mutation mode has been exhausted. */ bool candidate(input_slot *slot) { switch (mut_mode) { case M_HAVOC: { return havoc_candidate(slot); } case M_SLIDING: { return sliding_candidate(slot); } case M_STRUCTURED: { return structured_candidate(slot); } case M_DUMMY: { return dummy_candidate(slot); } case M_MANUAL: { return manual_candidate(slot); } } __builtin_unreachable(); }
C
#include <stdbool.h> #include <stddef.h> #include <stdint.h> #include "libc.h" extern void receiverMain(); void senderMain() { char buffer[10]; int fd1[2], fd2[2], fd3[2]; //make pipes pipe(fd1); pipe(fd2); //fork child pid_t childId = fork(1); if(childId == 0) { while(read(fd1[0], buffer, sizeof(buffer))) { continue; } write(1, buffer, sizeof(buffer)); write(fd2[1], "second\n", 7); while(read(fd1[0], buffer, sizeof(buffer))) { continue; } write(1, buffer, sizeof(buffer)); write(fd2[1], "fourth\n", 7); } else { write(fd1[1], "first\n", 6); while(read(fd2[0], buffer, sizeof(buffer))) { continue; } write(1, buffer, sizeof(buffer)); write(fd1[1], "third\n", 6); while(read(fd2[0], buffer, sizeof(buffer))) { continue; } write(1, buffer, sizeof(buffer)); } exit(EXIT_SUCCESS); }
C
/***************************************************************************** *Author:Diego Silva *Date:29/03/2021 *Description:Code active led to using pull up resistor *****************************************************************************/ #define F_CPU 16000000 #define ATIVADO 1 #define ESPERA 2000 #include <avr/io.h> #include <util/delay.h> //prototipação de metodos void incializa_portas(void); int checa_chave(void); void libera_acesso(void); int main(){ //Inicializando portas incializa_portas(); while(1){ //estado alto da porta PORTB |= (1<<PORTB5); //checa se a chave foi acionada if( checa_chave() == ATIVADO){ libera_acesso(); } } return 0; } /*************************************************************** * * DD5 - porta digital como OUTPUT * DD4 - porta digital como INPUT * DD0 - porta digital como OUTPUT * *************************************************************/ void incializa_portas(void){ DDRB |= (1<<DDB5); DDRB |=(1<<DDB4); DDRB &=~ (1<<DDB0); } /********************************** * Pegar valor de entrada * *******************************/ int checa_chave(void){ return (PINB&(1<<PINB0)); } /*********************************************** * Desativa porta DDB5 * Ativa Porta DDB0 * *********************************************/ void libera_acesso(void){ //desativa porta _delay_ms(ESPERA); PORTB &=~ (1<<PORTB5); _delay_ms(ESPERA); PORTB |= (1<<PORTB4); _delay_ms(ESPERA); PORTB &=~ (1<<PORTB4); _delay_ms(ESPERA); }
C
// fix this dead loop // the condition (!(value==10) || !(value==20)) cannot be arbitrarily changed. // You are only allowed to change two characters on the condition (!(value==10) || !(value==20)) int value; do { value=10; }while(!(value==10) || !(value==20))
C
#include "func.h" void recv_file(int sfd, char *filename){ int len; char buf[MAXBUFSIZE]; int ret; //接收文件名 //先接收文件名 bzero(buf,sizeof(buf)); ret=recv(sfd,&len,sizeof(len),0); // printf("len:%d\n", len); recv(sfd,buf,len,0); // printf("buf:%s\n", buf); int fd; /* fd=open(buf,O_CREAT|O_RDWR,0600); if(-1==fd) { perror("open"); // close(sfd); return; } */ recv_n(sfd, &len, 4); if(-1 == len){//服务器端文件不存在 goto end; } //else if(0 == len){ //服务器端文件存在 off_t filesize; off_t filesize_tmp; recv_n(sfd, &filesize, sizeof(filesize)); fd=open(buf,O_CREAT|O_RDWR|O_EXCL,0600); struct stat filestat; if(-1==fd) { fd = open(buf, O_RDWR|O_APPEND); if(-1 == fd){ perror("open 2"); } fstat(fd, &filestat); //文件已经存在 if(filesize == filestat.st_size){ //文件已经下载完毕 printf("文件已经下载完毕\n"); filesize_tmp = 0; send_n(sfd, &filesize_tmp, sizeof(filesize_tmp)); }else{ //文件还未下载完毕,从文件尾部开始下载 printf("文件还未下载完毕,需继续下载\n"); filesize_tmp = filestat.st_size; send_n(sfd, &filesize_tmp, sizeof(filesize_tmp)); fd = open(buf, O_RDWR|O_APPEND); if(-1 == fd){ perror("open 2"); } while(1) { recv_n(sfd,&len,sizeof(len));//先读4个字节 if(len>0) { bzero(buf,sizeof(buf)); recv_n(sfd,buf,len); write(fd,buf,len); }else{ break; } } } }else if(0 == filesize){ //文件大小为0,不需要下载 printf("文件大小为0,不需要下载\n"); filesize_tmp = -2; send_n(sfd, &filesize_tmp, sizeof(filesize_tmp)); }else{ //文件不存在,正常下载流程,从头下载 printf("文件不存在,正常流程从头开始下载\n"); filesize_tmp = 1; send_n(sfd, &filesize_tmp, sizeof(filesize_tmp)); while(1) { recv_n(sfd,&len,sizeof(len));//先读4个字节 if(len>0) { bzero(buf,sizeof(buf)); recv_n(sfd,buf,len); write(fd,buf,len); }else{ break; } } } printf("recv end\n"); close(fd); end: return; } int send_file(int new_fd, char *filename) { train t;//定义小火车 //第一步传输文件名 bzero(&t,sizeof(t)); t.len=strlen(filename); strcpy(t.buf,filename); int len; send(new_fd,&t,4+t.len,0);//发送文件名到客户端 //发送文件内容 // printf("len:%d buf:%s\n", t.len, t.buf); int fd; int ret; fd=open(filename,O_RDWR); if(-1==fd) { //服务器端文件不存在 perror("open"); len = -1; send_n(new_fd, &len, 4); // close(new_fd); return -1; }else{ //服务器端文件存在,可以下载 len = 0; send_n(new_fd, &len, 4); struct stat filestat; fstat(fd, &filestat); // printf("filename:%s st_size:%ld\n", filename, filestat.st_size); off_t filesize = filestat.st_size; send_n(new_fd, &filesize, sizeof(filesize)); off_t filesize_c; recv_n(new_fd, &filesize_c, sizeof(filesize_c)); if(0 == filesize_c){ //文件已经在客户端完整存在 printf("文件已经在客户端完整存在\n"); goto end; } /* char *p = (char*)mmap(NULL, filestat.st_size, PROT_READ,MAP_SHARED,fd,0); if(p == (char*)-1){ perror("mmap"); return -1; }*/ off_t total = filestat.st_size; // char *q = p; off_t offset; if(1 == filesize_c){ //文件不在客户端存在,需从头下载 offset = 0; printf("文件不在客户端,需从头下载大小:%ld\n", total); }else{ //文件在客户端, 需继续下载 total -= filesize_c; offset = filesize_c; printf("文件在客户端,需要继续下载大:%ld\n", total); } sendfile_n(new_fd, fd, &offset, total); /* while(total > 0){ if(total > 1000){ t.len = 1000; }else if(total > 0){ t.len = total; }else{ break; } memcpy(t.buf, q, t.len); ret = send_n(new_fd, &t, 4+t.len); if(-1 == ret){ goto end; } total -= t.len; q += t.len; } munmap(p, filestat.st_size); */ //发送结束 // t.len = 0; // send(new_fd, &t.len, 4, 0); } printf("send end!\n"); end: close(fd); // close(new_fd); return 0; }
C
#include "tree.h" //static functions /* * used for find the first * node in the tree */ static struct node* tree_frist_node(struct tree* tree) { struct node* node = tree->root; while(node->left) node = node->left; return node; } /* * used for find the last * node in the tree */ static struct node* tree_last_node(struct tree* tree) { if (!tree->root) return 0x0; struct node* node = tree->root; while(node->right) node = node->right; return node; } /* * used for find * a node by key */ static struct node* tree_get_node(struct tree* tree,int key){ if (!tree->root) return 0x0; struct node* node = tree->root; while(node && node->key != key) node = key > node->key ? node->right : node->left; return node; } static int tree_balancing_node(struct node* node){ if (!node) return 0; int left = node->left ? node->left->height+1 : 0; int right = node->right ? node->right->height+1 : 0; return left - right; } static void tree_set_height_node(struct node* node){ int left_level = node->left ? node->left->height+1 : 0; int right_level = node->right ? node->right->height+1 : 0; node->height = left_level > right_level ? left_level : right_level; } static void tree_left_rotation(struct node* node,struct tree* tree) { struct node* rigth = node->right; node->right = rigth->left; if (rigth->left) rigth->left->father = node; rigth->left = node; rigth->father = node->father; node->father = rigth; if (tree->root->key == node->key) tree->root = rigth; else { if (rigth->father->left && rigth->father->left->key == node->key) rigth->father->left = rigth; else rigth->father->right= rigth; } tree_set_height_node(node); } static void tree_right_rotation(struct node* node,struct tree* tree) { struct node* left = node->left; node->left = left->right; if (left->right) left->right->father = node; left->right= node; left->father = node->father; node->father = left; if (tree->root->key == node->key){ tree->root = left; } else { if (left->father->left && left->father->left->key == node->key) left->father->left = left; else left->father->right= left; } tree_set_height_node(node); } static void tree_double_rotation_left(struct node* node,struct tree* tree) { tree_right_rotation(node->right,tree); tree_left_rotation(node,tree); } static void tree_double_rotation_right(struct node* node,struct tree* tree) { tree_left_rotation(node->left,tree); tree_right_rotation(node,tree); } static void tree_update_height(struct node* node,struct tree* tree, type_rotation tr ) { tree_set_height_node(node); int level = node->height; while(node) { node->height = level++; //left rotations if (tree_balancing_node(node) <= -2) { if (tr == REMOVE) tree_left_rotation(node,tree); else { if (tree_balancing_node(node->right) < 0) tree_left_rotation(node,tree); else tree_double_rotation_left(node,tree); } //right rotation } else if (tree_balancing_node(node) >= 2) { if (tr == REMOVE) tree_right_rotation(node,tree); else { if(tree_balancing_node(node->left) > 0) tree_right_rotation(node,tree); else tree_double_rotation_right(node,tree); } } //new level level = node->height+1; node = node->father; } } /* * used for remove one node * of tree */ static void* tree_remove_node(struct node* node,struct tree* tree) { if (!node) return 0x0; struct node* father; struct node* aux; void* value = node-> value; father = node->father; //is leaf! if (!node->left && !node->right) { if (father->left == node) father->left = 0x0; else father->right = 0x0; free(node); tree_update_height(father,tree,REMOVE); } //the node have only one child else if (!node->left || !node->right){ //left if (node->left && !node->right) aux = node->left; //right else if (!node->left && node->right) aux = node->right; //node is root if (!node->father) tree->root=aux; else if (father->left == node) father->left = aux; else father->right = aux; aux->father = father; free(node); tree_update_height(aux,tree,REMOVE); } //the node have two child else { aux = node->right; while (aux->left) aux = aux->left; struct node* right = aux->right; node->key = aux->key; node->value = aux->value; right->father = aux->father; aux->father->left = right; node->height--; tree_update_height(right,tree,REMOVE); free(aux); } tree->size--; return value; } //end static functions struct tree* create_tree(){ return (struct tree*)malloc(sizeof(struct tree)); } int tree_is_empty(struct tree* tree) { return tree->size == 0; } void tree_insert(struct tree* tree, void* value, int key) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->value = value; if (!tree->root) tree->root = node; else { struct node* aux = tree->root; while (aux) { if (aux->key == key) { aux->value = value; break; } if (aux->key > key && !aux->left) { aux->left = node; node->father = aux; break; } else if (aux->key < key && !aux->right) { aux->right = node; node->father = aux; break; } aux = key > aux->key ? aux->right : aux->left; } tree->size++; tree_update_height(node,tree,INSERT); } } void* tree_get(struct tree* tree,int key){ struct node* node = tree_get_node(tree,key); return !node ? 0x0 : node->value; } void* tree_remove(struct tree* tree, int key){ return tree_remove_node(tree_get_node(tree,key),tree); } void tree_print(struct tree* tree ){ struct Queue* queue = new_queue(); struct node* node; add(queue,tree->root); while(!isEmpity(queue)){ node = getFirst(queue); if (node->left) add(queue,node->left); if (node->right) add(queue,node->right); printf("%s ","{"); printf("key: %d - ",node->key); if (node->father) { if (node->father->left && node->father->left->key == node->key) printf("child left: %d ",node->father->key); else printf("child rigth: %d ",node->father->key); } else printf("root node - "); printf("height: %d ",node->height); printf(" bf: %d ",tree_balancing_node(node)); printf("%s\n","}"); } } void* tree_first(struct tree* tree) { if (!tree->root) return 0x0; return tree_frist_node(tree)->value; } void* tree_remove_first(struct tree* tree){ if (!tree->root) return 0x0; return tree_remove_node(tree_frist_node(tree),tree); } void* tree_last(struct tree* tree) { if (!tree->root) return 0x0; return tree_last_node(tree)->value; } void* tree_remove_last(struct tree* tree) { if (!tree->root) return 0x0; return tree_remove_node(tree_last_node(tree),tree); }
C
/* Bit plane encoder Please note: (1) Before you download and use the program, you must read and agree the license agreement carefully. (2) We supply the source code and program WITHOUT ANY WARRANTIES. The users will be responsible for any loses or damages caused by the use of the source code and the program. Author: Hongqiang Wang Department of Electrical Engineering University of Nebraska-Lincoln Email: hqwang@bigred.unl.edu, hqwang@eecomm.unl.edu Your comment and suggestions are welcome. Please report bugs to me via email and I would greatly appreciate it. March 9, 2008 */ #include <string.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "getopt.h" #include "global.h" //#define DEMO extern void EncoderEngine(StructCodingPara * PtrCoding); extern void DecoderEngine(StructCodingPara * PtrCoding); extern void HeaderInilization(StructCodingPara *Ptr); void DebugInfo(char *m); #define VERSION "Last modified on March 9, 2008\n" #define DEBUG #ifndef DEBUG #define DEBUG #endif void Usage() { fprintf(stderr, "/****************** Bit Plane Encoder Using Wavelet Transform ************/\n"); fprintf(stderr, VERSION); fprintf(stderr, "bpe [-e]/[-d] [Input_file_name] [-o Output_file_name] [-r BitsPerPixel]\n"); fprintf(stderr, "\nParameters: \n"); fprintf(stderr, "[-e]: encoding filename; \n"); fprintf(stderr, "[-d]: decoding filename; \n"); fprintf(stderr, "[-o]: provide ouput file name. \n"); fprintf(stderr, "[-r]: bits per pixel for encoding. (by default it is 0 and encoded to the last bitplane\n"); fprintf(stderr, "[-w]: the number of pixels of each row. \n"); fprintf(stderr, "[-h]: the number of pixels of each column. \n"); fprintf(stderr, "[-b]: the number of bits of each pixel. By default it is 8.\n"); fprintf(stderr, "[-f]: byte order of a pixel, if it consists of more than one bytes.\n 0 means litttle endian, 1 means big endian. Default value is 0.\n"); fprintf(stderr, "[-t]: wavelet transform. 1 is integer 9-7 DWT and 0 is floating 9-7 DWT. By default it is integer DWT\n"); fprintf(stderr, "[-s]: the number of blocks in each segment. By default it is 256.\n"); fprintf(stderr, "eg 1: bpe -e sensin.img -o codes -r 1.0 -w 256 -h 256 -s 256 \n"); fprintf(stderr, "eg 2: bpe -d codes -o ss.img \n"); fprintf(stderr, "************* Author: Hongqiang Wang *******************************\n"); fprintf(stderr, "************* Department of Electrical Engineering ********************\n"); fprintf(stderr, "************* University of Nebraska -Lincoln **************************\n"); fprintf(stderr, "************* March 9, 2008 ******************************************\n"); fprintf(stderr, "/*******************************************************************\n"); return; } BOOL ParameterValidCheck(StructCodingPara *PtrCoding) { if((PtrCoding->PtrHeader->Header.Part2.SegByteLimit_27Bits != 0) &&( PtrCoding->BitsPerPixel <= 0 )) return FALSE; if ((PtrCoding->ImageWidth < IMAGE_WIDTH_MIN) || (PtrCoding->ImageWidth > IMAGE_WIDTH_MAX)) return FALSE; if (PtrCoding->ImageRows < IMAGE_ROWS_MIN) return FALSE; if (PtrCoding->PtrHeader->Header.Part3.S_20Bits < SEGMENT_S_MIN) return FALSE; if((PtrCoding->BitsPerPixel < 0) || (PtrCoding->BitsPerPixel >16)) return FALSE; return TRUE; } /************************************************/ #ifndef DEBUG #define DEBUG #endif int main(int argc, char **argv) { extern char *optarg; char i = 0; long TotalPixels = 0; char StringBuffer[100] = {""}; StructCodingPara *PtrCoding = NULL; BOOL BoolEnCoder = FALSE; BOOL BoolDeCoder = FALSE ; time_t t0, t1; /* time_t defined in <time.h> and <sys/types.h> as long */ clock_t c0, c1; /* clock_t defined in <time.h> and <sys/types.h> as int */ // F_CodingInfo = NULL; PtrCoding = (StructCodingPara *) calloc(sizeof(StructCodingPara), 1); HeaderInilization(PtrCoding); // demonstration mode i DEMO is defined. Please make sinan.img available in the current directory. //#ifndef DEMO //#define DEMO //#endif #ifdef DEMO fprintf(stderr, "Demo mode:\n\t Input image: sinan.img, \n\t Bitrate = 1.0, \n\t Segment = 1024; \n\t Transform: Int97\n"); strcpy(PtrCoding->InputFile, "sinan.img"); BoolEnCoder = TRUE; PtrCoding->BitsPerPixel = 1; PtrCoding->ImageRows = 256; PtrCoding->ImageWidth = 256; PtrCoding->PtrHeader->Header.Part3.S_20Bits = 1024; if(BoolEnCoder == TRUE) { strcpy(PtrCoding->CodingOutputFile, PtrCoding->InputFile); strcat(PtrCoding->CodingOutputFile, ".out"); } else { strcpy(PtrCoding->CodingOutputFile, PtrCoding->InputFile); strcat(PtrCoding->CodingOutputFile, ".dec"); strcat(PtrCoding->InputFile, ".out"); } #else //********************************************************* while((i = getopt(argc,argv,"e:d:o:r:h:w:b:f:t:s:g:"))!=EOF) { switch (i) { case 'e': BoolEnCoder = TRUE; // encoder. strcpy(PtrCoding->InputFile, optarg); break; case 'd': BoolDeCoder = TRUE; // decoder strcpy(PtrCoding->InputFile, optarg); break; case 'o': strcpy(PtrCoding->CodingOutputFile,optarg); break; case 'r': // coding BitsPerPixel, bits per pixels strcpy(StringBuffer,optarg); PtrCoding->BitsPerPixel = (float)atof(StringBuffer); break; case 'h': // row size strcpy(StringBuffer, optarg); PtrCoding->ImageRows = atoi(StringBuffer); break; case 'w': // col size strcpy(StringBuffer, optarg); PtrCoding->ImageWidth = atoi(StringBuffer); break; case 'f': // flip order. 0: little endian (LSB first) // usually for intel processor, it is 0, the default value. //, 1: big endian // If it is 1, byte order will be changed later. strcpy(StringBuffer, optarg); PtrCoding->PixelByteOrder = atoi(StringBuffer); break; case 'b': // bit per pixel strcpy(StringBuffer, optarg); // PtrCoding->PtrHeader->Header.Part4.PixelBitDepth_4Bits = atoi(StringBuffer) * 8; PtrCoding->PtrHeader->Header.Part4.PixelBitDepth_4Bits = atoi(StringBuffer) % 16; break; case 't': // type of wavelet transform strcpy(StringBuffer, optarg); PtrCoding->PtrHeader->Header.Part4.DWTType = atoi(StringBuffer); break; case 'g': // signed pixels or not strcpy(StringBuffer, optarg); PtrCoding->PtrHeader->Header.Part4.SignedPixels = atoi(StringBuffer); if(PtrCoding->PtrHeader->Header.Part4.SignedPixels > 0) PtrCoding->PtrHeader->Header.Part4.SignedPixels = TRUE; else PtrCoding->PtrHeader->Header.Part4.SignedPixels= FALSE; break; case 's': strcpy(StringBuffer, optarg); PtrCoding->PtrHeader->Header.Part3.S_20Bits = atoi(StringBuffer); break; default: Usage(); strcpy(StringBuffer, "CodingInfo.txt"); /* if ((F_CodingInfo = fopen(StringBuffer,"w")) == NULL) { fprintf(stderr, "Cannot creat coding information file. \n"); exit(0); } */ ErrorMsg(BPE_INVALID_CODING_PARAMETERS); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////// Validate coding parameters ////////////////////////////////////////////////////////////// if((BoolEnCoder && BoolDeCoder) || ((!BoolEnCoder) && (!BoolDeCoder)) || (strcmp(PtrCoding->CodingOutputFile, "") == 0) || // strcmp returns 0 if both strings are identical. (strcmp(PtrCoding->InputFile, "") == 0)) { strcat(StringBuffer, "En.txt"); /* if ((F_CodingInfo = fopen(StringBuffer,"w")) == NULL) { fprintf(stderr, "Cannot creat coding information file. \n"); exit(0); } */ Usage(); ErrorMsg(BPE_INVALID_CODING_PARAMETERS); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif if (BoolEnCoder == TRUE) { //store information to a text file. strcpy(StringBuffer, PtrCoding->CodingOutputFile); strcat(StringBuffer, "En.txt"); /* if ((F_CodingInfo = fopen(StringBuffer,"w")) == NULL) { fprintf(stderr, "Cannot creat coding information file. \n"); exit(0); } */ if((PtrCoding->BitsPerPixel != 0) && PtrCoding->PtrHeader->Header.Part2.SegByteLimit_27Bits == 0) PtrCoding->PtrHeader->Header.Part2.SegByteLimit_27Bits = PtrCoding->BitsPerPixel * PtrCoding->PtrHeader->Header.Part3.S_20Bits * 64/8; //check validility of the input parameters. if (ParameterValidCheck(PtrCoding) == FALSE) ErrorMsg(BPE_INVALID_CODING_PARAMETERS); // DebugInfo( "\tBegin to encode...\n"); // record the encoding time. t0 = time(NULL); c0 = clock(); EncoderEngine(PtrCoding); c1 = clock(); t1 = time(NULL); // DebugInfo( "\tEncoding Success!\n"); // fprintf (stderr, "\telapsed CPU time: %f\n", (float) (c1 - c0)/CLOCKS_PER_SEC); TotalPixels = PtrCoding->ImageRows * PtrCoding->ImageWidth; // fprintf(F_CodingInfo, "Success! %f ", (float) PtrCoding->Bits->TotalBitCounter/ TotalPixels); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (BoolDeCoder == TRUE) { short TotalBitsPerpixel = 0; //store information to a text file. strcpy(StringBuffer, PtrCoding->CodingOutputFile); strcat(StringBuffer, ".txt"); /* if ((F_CodingInfo = fopen(StringBuffer,"w")) == NULL) { fprintf(stderr, "Cannot creat coding information file. \n"); exit(0); } */ if(PtrCoding->BitsPerPixel < 0) ErrorMsg(BPE_INVALID_CODING_PARAMETERS); // DebugInfo( "\tBegin to decode...\n"); // record the decoding time. t0 = time(NULL); c0 = clock(); DecoderEngine(PtrCoding); c1 = clock(); t1 = time(NULL); // DebugInfo( "\tDecoding Success!\n"); // fprintf (stderr, "\telapsed CPU time: %f\n", (float) (c1 - c0)/CLOCKS_PER_SEC); TotalBitsPerpixel = PtrCoding->PtrHeader->Header.Part4.PixelBitDepth_4Bits; if(TotalBitsPerpixel == 0) TotalBitsPerpixel = 16; TotalPixels = PtrCoding->ImageRows * PtrCoding->ImageWidth; /* fprintf(F_CodingInfo, "%s %f %d %d %d", "Success!", (float) PtrCoding->Bits->TotalBitCounter/ TotalPixels, PtrCoding->ImageRows, PtrCoding->ImageWidth, TotalBitsPerpixel); */ } free(PtrCoding); // fclose(F_CodingInfo); return 0; }
C
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> void print_inode_stats(struct stat *stats, char *dateiname) { printf("Dateiname:\t\t\t%s\n",dateiname); printf("Gerätenummer:\t\t\t%ld\n", (long)stats->st_dev); printf("I-Node Nummer:\t\t\t%ld\n", (long)stats->st_ino); printf("Dateiart und Zugriffsrecht:\t%ld\n", (long)stats->st_mode); printf("Anzahl der Links:\t\t%ld\n", (long)stats->st_nlink); printf("User-Id:\t\t\t%ld\n", (long)stats->st_uid); printf("Group-Id:\t\t\t%ld\n", (long)stats->st_gid); printf("Geraetenummer:\t\t\t%ld\n", (long)stats->st_rdev); printf("Groesse in Byte:\t\t%ld\n", (long)stats->st_size); printf("Optimale Bockgroesse:\t\t%ld\n", (long)stats->st_blksize); printf("Anzahl belegter Bloecke:\t%ld\n", (long)stats->st_blocks); printf("Letzter Zugriff:\t\t%ld\n", (long)stats->st_atime); printf("Letzte Aenderung:\t\t%ld\n", (long)stats->st_mtime); printf("Aenderungszeit INode:\t\t%ld\n", (long)stats->st_ctime); printf("\n"); } int main(int argc, char **argv) { if (argc < 2) { printf("error: Rstat <Dateipfad>\n"); return EXIT_FAILURE; } struct stat stats; //ino_t inode_number = stats.st_ino; for (int i = 1; i < argc; i++) { if (stat(argv[i], &stats) < 0) perror("stat"); print_inode_stats(&stats, argv[i]); } return EXIT_SUCCESS; }
C
*문제 설명 -문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하세요. 제한 사항 -문자열 전체의 짝/홀수 인덱스가 아니라, 단어(공백을 기준)별로 짝/홀수 인덱스를 판단해야합니다. 첫 번째 글자는 0번째 인덱스로 보아 짝수번째 알파벳으로 처리해야 합니다. #include <stdio.h> #include <stdbool.h> #include <stdlib.h> // 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요. char* solution(const char* s) { // return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요. int count = 0, i = 0; int index =0; while(s[i++]){ // 문자열의 길이 구한다. count++; } char* answer = (char*)malloc(count+1); // 문자열을 변환하여 저장할 배열을 할당한다. answer[count] = '\0'; for(i=0;i<count;i++) { if (s[i] == ' ') { // 전체문자열의 인덱스가 아니고, 공백문자로 구분된 단어의 index =0; // 인덱스를 기준으로 , 홀/짝 을 구분하기 위해서 answer[i]=' '; // 공백문자를 만나면 index 변수를 초기화 해준다. continue; } else if (index % 2 == 0) { // 짝수 -> 대문자 (0도 짝수처리) if (((s[i] >= 'a') && (s[i] <= 'z'))) { answer[i] = s[i] - 0x20; } else if ((s[i] >= 'A') && (s[i] <= 'Z')) { answer[i] = s[i]; } } else{ if ((s[i] >= 'A') && (s[i] <= 'Z')) { answer[i] = s[i] + 0x20; } else if (((s[i] >= 'a') && (s[i] <= 'z'))) { answer[i] = s[i]; } } index++; } return answer; }
C
#include<stdio.h> #include<stdlib.h> #define T 10 int main() { int V[T], i, soma=0, produto=1; printf("\nDigite os valores para o vetor V:\n"); for(i=0;i<T;i++) { printf("V[%d] = ",i+1); scanf("%d",&V[i]); } for(i=0;i<T;i++) { soma += V[i]; produto *= V[i]; } printf("\nA soma dos componentes do vetor V eh:\nSoma = %d\n\nO produto dos componentes do vetor V eh:\nProduto = %d\n\n",soma,produto); return EXIT_SUCCESS; }
C
/* Zadatak 01 * Izračunati površinu trougla upotrebom * Heronovog obrasca */ #include <stdio.h> #include <math.h> int main() { //Stranice trougla double a = 2.0; double b = 4.0; double c = 5.0; //Računanje poluobima s = (a + b + c) / 2; //Računanje i ispis površine na dve decimale P = sqrt(s * (s - a) * (s - b) * (s - c)); printf("P=%.2lf\n", P); //Uspešan završetak programa return 0; }
C
/** * @file unit_test.h * @author Austin Glaser <austin.glaser@colorado.edu> * * @brief A testing library for standard c * * <Add more details> * * @addtogroup UNIT_TEST * @{ */ /* --- PRIVATE DEPENDENCIES ------------------------------------------------- */ // Module #include "unit_test.h" // Standard Libraries #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <malloc.h> /* --- PRIVATE MACROS ------------------------------------------------------- */ #define RED "\x1b[0;31;40m" /**< Control string to make red */ #define GREEN "\x1b[0;32;40m" /**< Control string to make green */ #define RESET "\x1b[0m" /**< Control string to reset modifiers */ #define N_PAD_CHARS 40 /**< Number of padding characters in the name */ #define N_LEFT_PAD 3 /**< Number of padding characters to the left */ /* --- PRIVATE DATA TYPES --------------------------------------------------- */ /** * @brief Structure for a single test */ typedef struct unit_test_node_t_ { char * name; /**< The test's name */ unit_test_pre_f_t pre; /**< The code used to initialize the test */ unit_test_body_f_t body; /**< The code used to execute the test */ unit_test_post_f_t post; /**< The code used to clean up after the test */ struct unit_test_node_t_ * next; /**< The next test to run */ } * unit_test_node_t; /** * @brief Unit test structure */ struct unit_test_t_ { char * test_name; /**< The name of this test suite */ uint32_t n_tests; /**< How many tests are registered */ unit_test_node_t head; /**< The linked list of tests */ }; /* --- PRIVATE FUNCTION PROTOTYPES ------------------------------------------ */ /** * @brief Inserts name into padded_name, */ static inline void unit_test_pad_string(char * string, char * padded_string, char pad, uint32_t n_left_pad, uint32_t n_pad_chars); /* --- PUBLIC FUNCTION DEFINITIONS ------------------------------------------ */ unit_test_t unit_test_create(char * test_name) { // Allocate memory unit_test_t tests = (unit_test_t) malloc(sizeof(struct unit_test_t_)); if (!tests) return NULL; // Initialize fields tests->test_name = test_name; tests->n_tests = 0; tests->head = NULL; return tests; } void unit_test_free(unit_test_t tests) { unit_test_node_t curr; unit_test_node_t next; if (tests) { // Free test nodes curr = tests->head; while (curr) { next = curr->next; free(curr); curr = next; } // Free structure free(tests); } } uint32_t unit_test_run(unit_test_t tests) { char * err_str; void * p_context; char padded_name[128]; bool passed; uint32_t i; uint32_t n_failed = 0; unit_test_node_t curr; // Print title and box // Box top printf("\n"); printf(" "); for (i = 0; i < N_PAD_CHARS + 9; i++) printf("="); printf("\n"); // Name unit_test_pad_string(tests->test_name, padded_name, '=', N_LEFT_PAD, N_PAD_CHARS + 9); printf(" %s\n", padded_name); // Box bottom printf(" "); for (i = 0; i < N_PAD_CHARS + 9; i++) printf("="); printf("\n"); // Loop over all registered tests for (curr = tests->head; curr; curr = curr->next) { // Run test. Will only run body if pre-test tasks succeed passed = curr->pre(&p_context, &err_str) && curr->body(p_context, &err_str); curr->post(p_context); // Pad name unit_test_pad_string(curr->name, padded_name, '-', N_LEFT_PAD, N_PAD_CHARS); // Print results if (passed) { printf(" %s [ " GREEN "PASS" RESET " ]", padded_name); } else { printf(" %s [ " RED "FAIL" RESET " ]", padded_name); n_failed++; } // Print error if there was one if (err_str && strlen(err_str) > 0) printf(": %s\n", err_str); else printf("\n"); } printf("\n"); return n_failed; } bool unit_test_register(unit_test_t tests, char * name, unit_test_pre_f_t pre, unit_test_body_f_t body, unit_test_post_f_t post) { // Check input if (!tests || !name || !pre || !body || !post) return false; // Allocate new node unit_test_node_t node = malloc(sizeof(struct unit_test_node_t_)); if (!node) return false; node->name = name; node->pre = pre; node->body = body; node->post = post; node->next = NULL; // Check if list is empty if (tests->head == NULL) { // Debug check assert(tests->n_tests == 0); // Insert test tests->head = node; (tests->n_tests)++; } else { // Find the end unit_test_node_t curr; for (curr = tests->head; curr->next; curr = curr->next); // Insert test curr->next = node; (tests->n_tests)++; } return true; } /* --- PRIVATE FUNCTION DEFINITIONS ----------------------------------------- */ static inline void unit_test_pad_string(char * string, char * padded_string, char pad, uint32_t n_left_pad, uint32_t n_pad_chars) { uint32_t i; // Fill with padding character memset(padded_string, pad, n_pad_chars); padded_string[n_pad_chars] = '\0'; // Put name in padded string padded_string[n_left_pad] = ' '; for (i = 0; i < strlen(string); i++) { padded_string[n_left_pad + 1 + i] = string[i]; } padded_string[n_left_pad + 1 + i] = ' '; } /** @} addtogroup UNIT_TEST */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tvermeil <tvermeil@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/01/12 15:22:25 by tvermeil #+# #+# */ /* Updated: 2016/03/17 14:08:13 by tvermeil ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void display_usage(char *command) { ft_putstr("usage: "); ft_putstr(command); ft_putstr(" [-v] [-c] nbr [...]\n"); exit(0); } void print_error(void) { ft_putstr("Error\n"); exit(0); } static int contains_invalid_flag(char *str) { while (*++str) { if (*str != 'c' && *str != 'v') return (1); } return (0); } static char *get_flags(int *ac, char **av[]) { char *flags; char *old; char *command; flags = NULL; command = **av; *ac -= 1; *av += 1; while ((**av)[0] == '-' && ((**av)[1] == 'c' || (**av)[1] == 'v')) { if (contains_invalid_flag(**av)) { free(flags); display_usage(command); } old = flags; flags = ft_strjoin(flags, **av + 1); free(old); *av += 1; *ac -= 1; } return (flags); } int main(int ac, char *av[]) { char *flags; char *command; char *op_list; t_pile *pile_tab[2]; command = av[0]; if (ac < 2) display_usage(command); flags = get_flags(&ac, &av); if (ac < 1) display_usage(command); pile_tab[0] = save_param_to_pile(ac, av, command); pile_tab[1] = NULL; if (has_duplicate(pile_tab[0])) print_error(); if (ft_strchr(flags, 'v')) print_piles(pile_tab); op_list = solve(pile_tab, flags); if (op_list == NULL) ft_putendl("Already sorted"); else ft_putendl(op_list); return (0); }
C
#include<stdio.h> int main() { int T; scanf("%d",&T); while(T--) { long long N; scanf("%lld",&N); long long i,k; k=N; for(i=1;i<N;i++) { printf("%lld ",k); long long g=N*(k-i); N=g; } //printf("N:%lld ",N); long long count=0; while(N%10==0) { N=N/10; count++; } printf("%lld\n",count); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <omp.h> #define NUM_THREADS 12 int main() { FILE *image, *outputImage, *lecturas; unsigned char* imgIni = (unsigned char*)malloc(226241*3*sizeof(unsigned char)); unsigned char* imgRes = (unsigned char*)malloc(226241*3*sizeof(unsigned char)); image = fopen("flores.bmp","rb"); //Imagen original a transformar outputImage = fopen("img22_dd.bmp","wb"); //Imagen transformada unsigned char r, g, b; //Pixel int j =0; for(int i=0; i<54; i++) fputc(fgetc(image),outputImage); while(!feof(image)){ *(imgIni+j)=fgetc(image); j++; } //copia adtos de imagen a al apuntador imgIni #pragma omp parallel { #pragma omp for ordered for (int i =0; i<226241*3; i+=3){ b = *(imgIni+i); g = *(imgIni+i+1); r = *(imgIni+i+2); unsigned char pixel = 0.21*r+0.72*g+0.07*b; #pragma omp ordered { *(imgRes+i)=pixel; //b *(imgRes+i+1)=pixel;//g *(imgRes+i+2)=pixel;//r } } } for (int i=0; i< 226241*3; i++){ fputc(*(imgRes + i), outputImage); } free(imgIni); free(imgRes); fclose(image); fclose(outputImage); return 0; }
C
#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> #include<windows.h> COORD coord={0,0}; void gotoxy(int x, int y) { coord.X=x; coord.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); } int main() { FILE *hFile,*ft; char another, choice; struct hardware { int record; char toolName[100]; int quantity; float cost; }; struct hardware e; char hName[40]; long int resize; hFile=fopen("EMP.dat","rb+"); if(hFile==NULL) { hFile = fopen("EMP.dat","wb+"); if(hFile==NULL) { printf("Can't open file"); exit(1); } } resize = sizeof(e); while(1) { system("cls"); printf("\n\n---------------------------------WElCOME TO TOOLBOX-----------------------------"); gotoxy(30,10); printf("1. Add Tool Details"); gotoxy(30,12); printf("2. All Saved Informaiton"); gotoxy(30,14); printf("3. Modify Information"); gotoxy(30,16); printf("4. Delete Information"); gotoxy(30,18); printf("5. Exit"); gotoxy(30,20); printf("Enter What you want to do: "); fflush(stdin); choice = getche(); switch (choice) { case '1': system("cls"); fseek(hFile,0,SEEK_END); another = 'y'; while(another=='y') { printf("\nEnter Tool Name: "); scanf("%s",e.toolName); printf("\nEnter record Name: "); scanf("%d",&e.record); printf("\nEnter Tool quantity: "); scanf("%d",&e.quantity); printf("\nEnter Tool cost: "); scanf("%f",&e.cost); fwrite(&e,resize,1,hFile); printf("\nAdd another record(y/n) "); fflush(stdin); another = getche(); } break; case '2': system("cls"); rewind(hFile); while(fread(&e,resize,1,hFile)==1) { printf("\n %s %d %d %.2f",e.toolName,e.record,e.quantity,e.cost); } getch(); break; case '3': system("cls"); another = 'y'; while (another == 'y') { printf("enter name to modify: "); scanf("%s",hName); rewind(hFile); while(fread(&e,resize,1,hFile)==1) { if(strcmp(e.toolName,hName)==0) { printf("\nEnter new name,quantity and salary:"); scanf("%d%s%d%f",e.record,e.toolName,&e.quantity,e.cost); fseek(hFile,-resize,SEEK_CUR); fwrite(&e,resize,1,hFile); break; } } printf("\nModify another record(y/n)"); fflush(stdin); another = getche(); } break; case '4': system("cls"); another = 'y'; while (another == 'y') { printf("\nEnter tool name to delete: "); scanf("%s",hName); ft = fopen("Temp.dat","wb"); rewind(hFile); while ((fread(&e,resize,1,hFile)==1)) { if(strcmp(e.toolName,hName)!=0) { fwrite(&e,resize,1,ft); } } fclose(hFile); fclose(ft); remove("EMP.dat"); rename("Temp.dat","EMP.dat"); hFile = fopen("EMP.dat","rb+"); printf("--*File has been deleted*--\n"); printf("Delete another record (y/n)"); fflush(stdin); another = getche(); } break; case '5': fclose(hFile); exit(0); } } return 0; }
C
#include <stdio.h> #include <string.h> //cria uma nova lista de arrays (arrays de arrays) .Primeira lista tem tamanho não definido, por isso é "Ilimitada" char tracks [][80] = { "i left my heart in Harvard Med School", "Newyork, Newyork...", "Dancing with a Dork", "From here to maternity", "The girl from Iwo Jima", }; void find_track(char search_for[]) { int i; for (i = 0; i < 5; i++) { // usa no minimo 5 chars pra encontrar uma palavra ("dork, left , heart") if(strstr(tracks[i], search_for))// se o resultado for encontrado printf("Track %i: %s\n", i, tracks[i]); //mostrar resultado } } int main() { char search_for[80];//adiciona o array de arrays que criamos printf("Search for: "); //pergunta ao usuario encontrar a musica a particar da letra fgets(search_for, 80, stdin);//semelhante ao scanf find_track(search_for); // agora chamamos a função search_for() return 0; }
C
#include "p18cxxx.h" unsigned char ReadPicEEPROM(unsigned char address){ EEADR=address; EECON1bits.EEPGD= 0; // 0 = Access data EEPROM memory EECON1bits.CFGS = 0; // 0 = Access Flash program or DATA EEPROM memory EECON1bits.RD = 1; // EEPROM Read return EEDATA; // return data } void WritePicEEPROM(unsigned char address,unsigned char data){ unsigned char INTCON_SAVE; EEADR = address; EEDATA = data; EECON1bits.EEPGD= 0; // 0 = Access data EEPROM memory EECON1bits.CFGS = 0; // 0 = Access Flash program or DATA EEPROM memory EECON1bits.WREN = 1; // enable writes to internal EEPROM INTCON_SAVE=INTCON; // Save INTCON register contants INTCON=0; // Disable interrupts, Next two lines SHOULD run without interrupts EECON2=0x55; // Required sequence for write to internal EEPROM EECON2=0xaa; // Required sequence for write to internal EEPROM EECON1bits.WR=1; // begin write to internal EEPROM INTCON=INTCON_SAVE; //Now we can safely enable interrupts if previously used Nop(); while (PIR2bits.EEIF==0)//Wait till write operation complete { Nop(); } EECON1bits.WREN=0; // Disable writes to EEPROM on write complete (EEIF flag on set PIR2 ) PIR2bits.EEIF=0; //Clear EEPROM write complete flag. (must be cleared in software. So we do it here) }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_float.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dmlitvin <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/04 16:33:11 by dmlitvin #+# #+# */ /* Updated: 2018/12/04 16:33:14 by dmlitvin ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static void check_width(char **buf, t_printf *info) { int slen; int i; char *new; slen = (int)ft_strlen(*buf); if (info->width > slen && info->zero == '0') { i = 0; new = ft_strnew(info->width); (!ft_isdigit(**buf)) ? new[i++] = *(*buf)++ : 0; while (info->width-- - slen) new[i++] = '0'; ft_strcat(new, *buf); free((ft_isdigit(*new)) ? *buf : *buf - 1); *buf = new; } } static void ft_itoa_accurace(__int128 data, t_printf *info, char **buf) { char *out; int accurace; accurace = (info->accurace == -1) ? 6 : info->accurace; out = ft_strnew(accurace); while (accurace--) { out[accurace] = data % 10 + 48; data /= 10; } info->accurace = -1; ft_strcat(ft_strcat(*buf, "."), out); free(out); } int print_float(t_printf *info, float data) { int accurace; char *buf; char *str; int len; buf = ft_strnew(80); (data < 0.0) ? *buf = '-' : 0; (!*buf && info->flags->plus) ? *buf = '+' : 0; (!*buf && info->flags->space) ? *buf = ' ' : 0; data = ABS(data); accurace = (info->accurace == -1) ? 6 : info->accurace; ft_strcat(buf, (str = ft_itoa10((__uint128_t)data))); data = data - ((__uint128_t)data); if (info->accurace) { while (accurace--) data *= (float)10.0; data += (float)0.5; ft_itoa_accurace((__uint128_t)data, info, &buf); } check_width(&buf, info); len = print_string(info, buf); free(str); free(buf); return (len); } int print_double(t_printf *info, long double data) { int accurace; char *buf; char *str; int len; buf = ft_strnew(80); (data < 0.0) ? *buf = '-' : 0; (!*buf && info->flags->plus) ? *buf = '+' : 0; (!*buf && info->flags->space) ? *buf = ' ' : 0; data = ABS(data); accurace = (info->accurace == -1) ? 6 : info->accurace; ft_strcat(buf, (str = ft_itoa10((__int128)data))); data -= (info->size) ? (double)(__int128)data : (long double)(__int128)data; if (info->accurace) { while (accurace--) data *= (info->size) ? (double)10.0 : (long double)10.0; data += (info->size) ? (double)0.5 : (long double)0.5; ft_itoa_accurace((__int128)data, info, &buf); } check_width(&buf, info); len = print_string(info, buf); free(str); free(buf); return (len); }
C
#include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> #include <sys/types.h> int main(int argc, char const *argv[]){ int client_to_server; char *myfifo = "/tmp/client_to_server_fifo"; int server_to_client; char *myfifo2 = "/tmp/server_to_client_fifo"; client_to_server = open(myfifo, O_WRONLY);// ESCREVER O CLIENTE char* str = malloc(100*sizeof(char)); char* str1 = malloc(100*sizeof(char)); char* myfifo_final = malloc(50*sizeof(char)); while(1){ int n; while((n=read(0,str,101))>0){ sprintf(str1,"%d",getppid()); strcpy(myfifo_final,myfifo2); strcat(myfifo_final,str1); printf("%s\n",myfifo_final); printf("---------------\n"); printf("%s\n",str1); strcat(str1," "); strcat(str1,str); strcpy(str,str1); write(1,"\ncmd message to serwer: \n",25); write(1,str,strlen(str)-1); write(client_to_server, str,strlen(str)); write(1,"\n",1); perror("Write:"); printf("%s\n",myfifo_final); server_to_client = open(myfifo_final, O_RDONLY); // LER O QUE O SERVER MANDA.REPARA QUE UM LÊ E OUTRO ESCREVE(NOS 2 FICHEIROS E SÃO ALTERNADOS) printf("%s\n",myfifo_final); read(server_to_client,str,2048); perror("Read:"); write(1,"----------\n",11); write(1,str,strlen(str)); printf("-------------\n"); printf("%s\n",str1); printf("---------------\n"); printf("%s\n",myfifo_final); str = calloc(100,sizeof(char)); str1 = calloc(100,sizeof(char)); myfifo_final = calloc(50,sizeof(char)); close(server_to_client); } } close(client_to_server); return 0; }
C
#include "heap.h" number left(number i) { return 2 * i; } number right(number i) { return 2 * i + 1; } number parent(number i) { return i / 2; } void scambia(number *a, number *b) { number tmp = 0; tmp = *a; *a = *b; *b = tmp; } void MoveUp(number *A, number i) { while (i != 1 && A[i] > A[parent(i)]) { scambia(&A[i], &A[parent(i)]); i = parent(i); } } void heapify(number *A, number i, size_t heap_size) { number l, r, largest; l = left(i); r = right(i); largest = i; if (l <= heap_size && A[l] > A[i]) largest = l; if (r <= heap_size && A[r] > A[i] && A[r] > A[largest]) largest = r; if (largest != i) { scambia(&A[i], &A[largest]); heapify(A, largest, heap_size); } } void build_heap(number *A, size_t heap_size) { for (size_t i = heap_size / 2; i >= 1; --i) heapify(A, i, heap_size); } void heapsort(number *A, size_t size) /*Scambia l'elemento + grande in cima al vettore heap con l'elemento + piccolo alla fine, esclude l'ultimo elemento(che diventato il + grande) e ripete l'operazione con il vettore parziale senza considerare l'ultimo elemento;*/ { number i; size_t heap_size; build_heap(A, size); heap_size = size; for (i = size; i >= 2; --i) { scambia(&A[1], &A[i]); heapify(A, 1, --heap_size); } }
C
// program to implement srtack using structure /* ALGO PUSH:: 1. If TOP = SIZE – 1, then: (a) Display “The stack is in overflow condition” (b) Exit 2. TOP = TOP + 1 3. STACK [TOP] = ITEM 4. Exit POP:: 1. If TOP < 0, then (a) Display “The Stack is empty” (b) Exit 2. Else remove the Top most element 3. DATA = STACK[TOP] 4. TOP = TOP – 1 5. Exit */ #include <stdio.h> #include <conio.h> #include <stdlib.h> #define size 10 struct stack { int top; int st[size]; }; typedef struct stack STACK; int is_empty(STACK *); int is_full(STACK *); void push(STACK *); void pop(STACK *); void peek(STACK *); void display(STACK *); int main() { int ch; STACK *sp = (STACK *)malloc(sizeof(STACK)); sp->top = -1; printf("\n\t\tSTACK IMPLEMENTATION\n"); while (1) { printf("\nMAIN MENU:\n"); printf("1. PUSH\n2. POP\n3. PEEK\n4. DISPLAY\n5. EXIT\n"); printf("\nenter your choice: "); scanf("%d", &ch); switch (ch) { case 1: push(sp); break; case 2: pop(sp); break; case 3: peek(sp); break; case 4: display(sp); break; case 5: printf("\nexiting..."); exit(0); break; default: printf("\ninvalid choice !\n\n"); break; } } return 0; } int is_empty(STACK *em) { if (em->top == -1) return 1; return 0; } int is_full(STACK *fu) { if (fu->top == size - 1) return 1; return 0; } void push(STACK *pu) { if (is_full(pu)) printf("\n\tSTACK OVERFLOW !\n"); else { int item; printf("\nenter element you want to push: "); scanf("%d", &item); pu->st[++pu->top] = item; // printf("\n%d pushed into the stack successfully !\n", item); display(pu); } } void pop(STACK *po) { if (is_empty(po)) printf("\n\tSTACK UNDERFLOW !\n"); else { int item = po->st[po->top--]; // printf("\n%d popped successfully !\n", item); display(po); } } void peek(STACK *pe) { if (is_empty(pe)) printf("\n\tSTACK UNDERFLOW !\n"); else { int item = pe->st[pe->top]; printf("\n%d is peek element !\n", item); } } void display(STACK *di) { if (is_empty(di)) printf("\n\tSTACK IS EMPTY !\n"); else { for (int i = di->top; i >= 0; i--) printf("%d\n", di->st[i]); } }
C
#include "halfword_data_transfer.h" #include "../../common/log.h" #include "../sign_extension.h" word rotate_right(word value, word amount) { amount &= 31u; return (value >> amount) | (value << (-amount & 31u)); } void halfword_dt_io(arm7tdmi_t* state, bool p, bool u, bool w, bool l, byte rn, byte rd, word offset, bool s, bool h) { unimplemented(p == 0 && w == 1, "When p is 0, this bit must also always be 0!") if (p == 0) { w = true; } // Writeback always enabled when p == 0 unimplemented(s == 0 && h == 0, "This is actually a SWP instruction, something went wrong and execution shouldn't be here") word addr = get_register(state, rn); if (p) { if (u) { addr += offset; } else { addr -= offset; } } if (l) { if (!s && h) { // LDRH: Load unsigned halfword (zero extended) half value = state->read_half(addr); set_register(state, rd, rotate_right(value, (addr & 1u) << 3u)); } else if (s && !h) { //LDRSB: Load signed byte (sign extended) word value = state->read_byte(addr); set_register(state, rd, sign_extend_word(value, 8, 32)); } else if (s && h) { // LDRSH: Load signed halfword (sign extended) word value; if (addr & 1) { value = state->read_byte(addr); value = sign_extend_word(value, 8, 32); } else { value = state->read_half(addr); value = sign_extend_word(value, 16, 32); } set_register(state, rd, value); } } else { logdebug("p: %d, u: %d, w: %d, l: %d, rn: %d, rd: %d, offset: %d, s: %d, h: %d", p, u, w, l, rn, rd, offset, s, h) if (!s && h) { // Store halfword unimplemented(rd == 15, "Special case for R15: PC") state->write_half(addr, get_register(state, rd)); } else if (s && !h) { // Load doubleword logfatal("ldrd unimplemented (is this caught by LDR?)") } else if (s && h) { // Load halfword logfatal("strd unimplemented (is this caught by STR?)") } } if (w && (!l || rd != rn)) { if (!p) { if (u) { addr += offset; } else { addr -= offset; } } set_register(state, rn, addr); } } void halfword_dt_ro(arm7tdmi_t* state, bool p, bool u, bool w, bool l, byte rn, byte rd, bool s, bool h, byte rm) { halfword_dt_io(state, p, u, w, l, rn, rd, get_register(state, rm), s, h); }
C
#include "holberton.h" #include <stdio.h> #include <stdlib.h> /** * _strdup - return pointer to newly allocated space with copy of array * @str: original array * Return: the pointer to new string */ char *_strdup(char *str) { int a; /* length */ int b; char *ar; if (str == NULL) { return (NULL); } for (a = 0; *(str + a) != '\0'; a++) {} ar = malloc(sizeof(char) * a + 1); if (ar == NULL) { return (NULL); } for (b = 0; b < a; b++) { ar[b] = str[b]; } ar[b] = '\0'; return (ar); }
C
// // This file was generated by the Retargetable Decompiler // Website: https://retdec.com // #include <stdint.h> #include <stdio.h> #include <stdlib.h> // ------------------- Function Prototypes -------------------- int32_t insert(int32_t result, int32_t a2); int32_t printout(int32_t a1); // ------------------------ Functions ------------------------- // Address range: 0x804845d - 0x80484c8 int32_t insert(int32_t result, int32_t a2) { int32_t * v1 = (int32_t *)result; // 0x8048466 int32_t v2 = *v1; // 0x8048466 if (v2 == 0) { // 0x804846c *v1 = a2; // 0x80484c6 return result; } int32_t v3 = *(int32_t *)a2; // 0x8048479 int32_t v4 = *(int32_t *)v2; // 0x8048480 if (v3 < v4) { // 0x80484c6 return insert(v2 + 8, a2); } int32_t result2 = v4; // 0x80484ad if (v3 > v4) { // 0x80484af result2 = insert(v2 + 4, a2); } // 0x80484c6 return result2; } // Address range: 0x80484c8 - 0x8048515 int32_t printout(int32_t a1) { int32_t v1 = *(int32_t *)(a1 + 8); // 0x80484d1 if (v1 != 0) { // 0x80484d8 printout(v1); } // 0x80484e6 printf("%d\n", *(int32_t *)a1); int32_t v2 = *(int32_t *)(a1 + 4); // 0x80484fe int32_t result = 0; // 0x8048503 if (v2 != 0) { // 0x8048505 result = printout(v2); } // 0x8048513 return result; } // Address range: 0x8048515 - 0x8048592 int main(int argc, char ** argv) { int32_t v1 = 0; // bp-28, 0x804851e for (int32_t i = 1; i < 11; i++) { int32_t * mem = malloc(12); // 0x8048537 int32_t v2 = (int32_t)mem; // 0x8048537 *(int32_t *)(v2 + 4) = 0; *(int32_t *)(v2 + 8) = 0; *mem = rand(); insert((int32_t)&v1, v2); } // 0x8048584 return printout(v1); } // --------------- Dynamically Linked Functions --------------- // void * malloc(size_t size); // int printf(const char * restrict format, ...); // int rand(void); // --------------------- Meta-Information --------------------- // Detected compiler/packer: gcc (4.8.1) // Detected functions: 3
C
/* ** EPITECH PROJECT, 2018 ** 42sh ** File description: ** left redirection */ #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include "my.h" #include "redirect.h" int simple_left(int io[2], list_t *cmd) { char *file_name = cmd->next[SEPARATOR]->next[CMD]->cmd[0]; int mod = O_RDONLY; int fd = open(file_name, mod); if (fd == -1) { my_printf("%s: no such file o directorie\n", file_name); return (-1); } io[INPT] = fd; rm_node(cmd->next[SEPARATOR]); return (1); } static int write_in_pipe(char *word) { int tmp[2] = {0, 1}; char *str = NULL; if (pipe(tmp) == -1) return (-1); write(1,">", 1); str = get_next_line(0); while (str && my_strcmp(str, word) != 0) { write(tmp[1], str, my_strlen(str)); write(tmp[1],"\n", 1); free(str); write(1,">", 1); str = get_next_line(0); } close(tmp[1]); return (tmp[0]); } int double_left(int io[2], list_t *cmd) { char *word = cmd->next[SEPARATOR]->next[CMD]->cmd[0]; int fd = 0; fd = write_in_pipe(word); if (fd == -1) return (-1); io[INPT] = fd; rm_node(cmd->next[SEPARATOR]); return (0); }
C
#include <stdio.h> int isOpen(int year); int main(void){ int year; int ret ; scanf("%d",&year); ret = isOpen(year); if(ret == 0){ printf("開催\n"); }else{ printf("開催しない\n"); } return ret; } int isOpen(int year){ enum{ OPEN, CLOSE, }; if(year % 2 == 0){ return OPEN; } return CLOSE; }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #pragma section(".unknown", read) __declspec(allocate(".unknown")) const int unk_variable = 0x11223344; __declspec(code_seg(".func")) static int segment_function() { return 0x11223344; } int main() { uint8_t stack_memory[1000] = {0}; uint8_t *dynamic_memory = 0; fprintf(stdout, "Section : 0x%p\n", (void *) &unk_variable); fprintf(stdout, "Stack : 0x%p\n", (void *) stack_memory); dynamic_memory = calloc(1000, 1); fprintf(stdout, "Dyn[calloc]: 0x%p\n", (void *) dynamic_memory); free(dynamic_memory); dynamic_memory = malloc(1000); fprintf(stdout, "Dyn[malloc]: 0x%p\n", (void *) dynamic_memory); free(dynamic_memory); return segment_function(); }
C
#include <stdio.h> #include <stdlib.h> #define T 2 //Constante T que determina o tamanho da Arv.B #define MAX_CHAVES ( 2 * T - 1 ) //Máximo de registros #define MAX_FILHOS ( 2 * T ) //Máximo de filhos #define MIN_CHAVES ( T - 1 ) //Mínimo de registros // estrutura 'tipo_arvore' struct arvore{ int contChaves; int chaves[MAX_CHAVES]; struct arvore *filhos[MAX_FILHOS]; int folha; }; typedef struct arvore tipo_arvore; tipo_arvore* insereArvB(tipo_arvore *raiz, int valor) { int flag; char valorRetorno, i; tipo_arvore *filhoDir, *novaRaiz; filhoDir = insere(raiz, valor, &flag, &valorRetorno); //Verifica se ocorreu a descida na árvore adequadamente, se há a necessidade de um novo nó como raiz if (flag) { novaRaiz = alocaNovoNo(); novaRaiz->contChaves = 1; novaRaiz->chaves[0] = valorRetorno; novaRaiz->filhos[0] = raiz; novaRaiz->filhos[1] = filhoDir; novaRaiz->folha = 0; return novaRaiz; } else { return raiz; } } //Função que busca pelo nó onde deve ser inserido o valor/chave e faz a quebra do nó, quando necessário tipo_arvore *insere (tipo_arvore *no, int valor, int *flag, int *valorRetorno){ int i, pos, meio; tipo_arvore *noAux, *filhoDir; if (no == NULL) { //Então o nó pai (anterior) é o nó onde deve ser feita a inserção, pois alcançou um nó folha *flag = 1; *valorRetorno = valor; return NULL; } else { //Executa a busca pelo nó onde o valor deve ser inserido pos = buscaBinaria (no, valor); //verifica/busca a posição //Identifica se a chave já está presente na árvore if ( (pos < no->contChaves) && (no->chaves[pos] == valor) ){ printf("O valor da chave já está presente na Árvore B!\n"); *flag = 0; } else { //Desce na árvore, buscando pelo nó folha onde deve ocorrer a inserção if ( no->chaves[pos] < valor){ pos++; } filhoDir = insere(no->filhos[pos], valor, flag, valorRetorno); //Executa chamada recursiva if ( *flag ) { //Se ocorreu a descida como esperado, então insere o valor no nó if ( no->contChaves < MAX_CHAVES) { //Verifica se há espaço no nó insereChave(no, *valorRetorno, filhoDir); *flag = 0; } else { //Então é preciso dividir o nó p/ poder inserir o valor noAux = alocaNovoNo(); meio = no->chaves[MIN_CHAVES]; //Insere metade das chaves no novo nó noAux->filhos[0] = no->filhos[MIN_CHAVES+1]; for (i = MIN_CHAVES+1; i < MAX_CHAVES; i++){ insereChave( noAux, no->chaves[i], no->filhos[i+1] ); } //Atualiza o nó ("apaga" as chaves transferidas for (i = MIN_CHAVES; i < MAX_CHAVES; i++) { no->chaves[i] = 0; no->filhos[i+1] = NULL; no->contChaves--; } //Verifica em qual dos novos nós o valor deve ser inserido e executa if ( pos <= MIN_CHAVES) { insereChave(no, *valorRetorno, filhoDir); } else { insereChave(noAux, *valorRetorno, filhoDir); } //Retorna o elemento do meio para ser inserido no nó pai e o filho direito da chave central *flag = 1; *valorRetorno = meio; return (noAux); } } } } } int main(int argc, char *argv[ ]){ }
C
/* ex8-1a.c */ #include <stdio.h> #include <stdlib.h> int main() { /* 定義一指向int資料型態的指標,並觀察其內容 */ int num = 100; int *ptr; /* ptr是一個指向int的指標 */ ptr = &num; /* ptr指向num的位址 */ /* 印出num的位址及內容 */ printf("num 在記憶體的位址為 %p\n", &num); printf("num 變數值為 %d\n", num); /* 印出ptr變數位址 */ printf("&ptr is %p\n", &ptr); /* 印出ptr所指向的位址 */ printf("ptr is %p\n", ptr); /* 印出ptr所指向位址的內容 */ printf("*ptr = %d\n", *ptr); system("PAUSE"); return 0; }
C
/* ** get_high_socre.c for get_high_score.c in /home/chauvi_d/Rendu-2015-Epitech/rendu/Systunix/PSU_2015_tetris/game ** ** Made by chauvi_d ** Login <chauvi_d@epitech.net> ** ** Started on Wed Mar 16 13:49:25 2016 chauvi_d ** Last update Sun Mar 20 18:22:25 2016 chauvi_d */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <curses.h> #include "map.h" #include "my.h" char *my_get_score(int nb) { int result; int divisor; char *str; int i; i = 0; divisor = 1; if ((str = malloc(sizeof(char) * 6)) == NULL) return (NULL); if (nb < 0) return (NULL); while ((nb / divisor) >= 10) divisor = divisor * 10; while (divisor > 0) { result = (nb / divisor) % 10; str[i] = 48 + result; divisor = divisor / 10; i++; } while (i != 6) str[i++] = 0; return (str); } int check_content(char *buff) { int i; i = 0; while (buff[i]) { if (buff[i] < '0' || buff[i] > '9') { write(2, "Wrong Highscore file\n", 21); return (-1); } i++; } return (0); } int get_high_score() { char *buff; int fd; int i; i = 0; buff = malloc(sizeof(char) * 6); if (buff == NULL) return (-1); fd = open("./game/.highscore", O_RDONLY | O_CREAT); if (fd == -1) { write(2, "Highscore file is missing\n", 28); return (-1); } i = read(fd, buff, 5); buff[i] = 0; if (check_content(buff) == -1) return (-1); i = my_getnbr(buff); if (i > 200000) return (-1); return (i); } int write_high_score(int score) { int fd; char *highscore; if (score > get_high_score()) { if ((fd = open("./game/.highscore", O_WRONLY)) == -1) { write(2, "Highscore file is missing\n", 28); return (-1); } highscore = my_get_score(score); write(fd, highscore, my_strlen(highscore) + 1); close(fd); } return (0); }
C
#include <stdio.h> #include <iostream> using namespace std; extern int kapitalizacja( int a, int b, char k, float p, float belka ); int main(int argc, char** argv) { int a,b = 0; char k = 0; float p = 0.0; float belka = 0.19; cout << "Kapital START? "; cin >> a; cout << "Kapital END? "; cin >> b; cout << "Roczna stopa procentowa? "; cin >> p; cout << "Kapitalizacja? (m,r)"; cin >> k; kapitalizacja( a, b, k, p, belka); return 0; }
C
#include<stdio.h> #include<string.h> char alph[]="abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; int main(){ int n; scanf("%d",&n); getchar(); while(n--){ char enc[75],dec[20]; char *words[40],*p; int wordCount=0,lendec,lenenc,i; fgets(enc,sizeof(enc),stdin); fgets(dec,sizeof(dec),stdin); lenenc=strcspn(enc,"\r\n"); lendec=strcspn(dec,"\r\n"); enc[lenenc]='\0'; dec[lendec]='\0'; p=strtok(enc," "); while(p!=0){ if(strlen(p)==lendec) words[wordCount++]=p; p=strtok(NULL," "); } for(i=0;i<26;i++){ int j,flag=0; char wtmp[lendec]; strcpy(wtmp,dec); for(j=0;j<lendec;j++){ wtmp[j]= alph[dec[j]-'a' + i]; } for(j=0;j<wordCount;j++){ if(!strcmp(words[j],wtmp)){ flag=1; break; } } if(flag) putchar(alph[i]); } putchar('\n'); } }
C
#include<stdio.h> #include<string.h> void strCombine(char *src,char *des); int main(){ char str1[100] = "hello";//if we are trying to use pointer variable then we will get run time error saying bus fault char str2[20] = "world"; strCombine(str1,str2); printf("%s\n",str1); return 0; } //this is my own function to combine two strings void strCombine(char *src,char *des){ while(*src!='\0') { src++; } while(*des!='\0'){ *src = *des; src++; des++; } *src = '\0'; }
C
// Strother Woog // 1618221 // CMPS 101 // 4/22/19 // Runs InsertSort on a List of indicies based on a String Array // Lex.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include"List.h" #define MAX_LEN 256 int main(int argc, char* argv[]){ int n, count = 0; FILE *in, *in2, *out; char line[MAX_LEN]; char *token; // check command line for correct number of arguments if( argc != 3 ){ printf("Usage: %s <input file> <output file>\n", argv[0]); exit(1); } // open files for reading and writing in = fopen(argv[1], "r"); in2 = fopen(argv[1], "r"); out = fopen(argv[2], "w"); // check if files are available if(in == NULL) { printf("Unable to open file %s for reading\n", argv[1]); exit(1); } if(out == NULL) { printf("Unable to open file %s for writing\n", argv[2]); exit(1); } // grab number of lines from input file while( fgets(line, MAX_LEN, in2) != NULL) { count++; } // initialize array of strings for the lines from input file char tokenlist[count][MAX_LEN]; // store each line from input file in array while( fgets(line, MAX_LEN, in) != NULL) { token = strtok(line, "\n"); while(token != NULL) { strcpy(tokenlist[n], line); token = strtok(NULL, "\n"); n++; } } // insert sort algorithm List L = newList(); prepend(L, 0); moveFront(L); for(int j = 1; j < count; j++) { strcpy(line, tokenlist[j]); moveFront(L); while(index(L) < j - 1){ moveNext(L); } while(strcmp(tokenlist[get(L)], line) > 0) { if(index(L) != 0) movePrev(L); else if(index(L) == 0) break; } if(strcmp(tokenlist[get(L)], line) < 0 ) { insertAfter(L, j); } else if(strcmp(tokenlist[get(L)], line) > 0 ) { insertBefore(L, j); } else { insertAfter(L, j); } moveBack(L); } // print list to output file moveFront(L); for(int i = 0; i < count; i++){ fprintf(out, "%s\n", tokenlist[get(L)]); if(i != count - 1) moveNext(L); } // free heap memory freeList(&L); // close all input and output files fclose(in); fclose(in2); fclose(out); return(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* o_va_arg.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hecampbe <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/21 22:52:31 by hecampbe #+# #+# */ /* Updated: 2019/09/17 16:43:02 by hecampbe ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char *o_none(va_list lst_arg, char *format) { unsigned int arg; char *str; arg = va_arg(lst_arg, unsigned int); str = octal_conversion(arg, format); return (str); } char *o_hh(va_list lst_arg, char *format) { unsigned char arg; char *str; arg = va_arg(lst_arg, unsigned int); str = octal_conversion(arg, format); return (str); } char *o_h(va_list lst_arg, char *format) { unsigned short int arg; char *str; arg = va_arg(lst_arg, unsigned int); str = octal_conversion(arg, format); return (str); } char *o_l(va_list lst_arg, char *format) { unsigned long int arg; char *str; arg = va_arg(lst_arg, unsigned long int); str = octal_conversion_long(arg, format); return (str); } char *o_ll(va_list lst_arg, char *format) { unsigned long long int arg; char *str; arg = va_arg(lst_arg, unsigned long long int); str = octal_conversion_longx2(arg, format); return (str); }
C
// // Sequence.c // TDA // // Created by Luis Romo on 16/10/17. // Copyright © 2017 Luis Romo. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include "Sequence.h" //typedef struct { // int step; // int next; //}sequence; struct sequence{ int step; int next; }; Sequence seq_create(int init){ // return sequence = malloc(sizeof(struct sequence)); return seq_createStep(init, 1); } Sequence seq_createStep(int init, int step){ Sequence s; s=0; s=(Sequence) malloc(sizeof(struct sequence)); if(s!=0){ s->step = step; s->next = init; return s; }return 0; } void seq_destory(Sequence s){ free(s); } int seq_next(Sequence s){ int a=s->next; s->next+=s->step; return a; }
C
#include"handler.h" void* request_handler(void* rw){ request request_buffer = *((struct msgargs*)rw)->reqbuffer; int writer = ((struct msgargs*)rw)->writer; handle_request(writer, &request_buffer); } void* handler(void* rw){ int reader = ((struct msgargs*)rw)->reader; int writer = ((struct msgargs*)rw)->writer; pthread_t req_tids[MAX_TABS]; request genreqbuffer, reqbuffers[MAX_TABS]; msgargs genmsgargs={reader, -1, &genreqbuffer, NULL}, msgbuffers[MAX_TABS]={-1, writer, NULL, NULL, -1, writer, NULL, NULL, -1, writer, NULL, NULL, -1, writer, NULL, NULL}; for (;;){ if (get_request(&genmsgargs) > 0){ if((genreqbuffer.slot>=0) &&(genreqbuffer.slot<=MAX_TABS)){ reqbuffers[genreqbuffer.slot] = genreqbuffer; msgbuffers[genreqbuffer.slot].reqbuffer = &reqbuffers[genreqbuffer.slot]; pthread_create(&req_tids[genreqbuffer.slot], NULL, request_handler, &msgbuffers[genreqbuffer.slot]); } } } } void init_handler(int reader, int writer){ msgargs rw = {reader, writer, NULL, NULL}; pthread_t handler_tid; pthread_create(&handler_tid, NULL, handler, (void *)&rw); }
C
/********************************************//** * Universidade de Brasilia * * Bruno Sanguinetti 18/0046063 \n * Gabriel Vasconcelos 16/0120781 \n * Leonardo de Almeida 15/0135491 \n * Lucas Mafra 12/0126443 \n * Wladimir Gramacho 15/0058718 \n ***********************************************/ /** * @file * @brief Cabeçalho do exibidor do classfile no terminal. \n * @section DESCRIPTION * * */ #ifndef PRINTER_H #define PRINTER_H /* Includes */ #include <stdlib.h> #include <stdio.h> #include "reader.h" /* Definitions */ #define ACC_PUBLIC 0x0001 /*!< \brief Declaracao: publico; pode ser acessada de fora do pacote. */ #define ACC_PRIVATE 0x0002 /*!< \brief Declaracao: privado; usavel apenas dentro da classe. */ #define ACC_PROTECTED 0x0004 /*!< \brief Declaracao: protected; usavel pela classe e subclasses. */ #define ACC_STATIC 0x0008 /*!< \brief Declaracao: statico. */ #define ACC_FINAL 0x0010 /*!< \brief Declaracao: final; after the member */ #define ACC_VOLATILE 0x0040 /*!< \brief Declaracao: classe abstrata */ #define ACC_TRANSIENT 0x0080 /*!< \brief Declaracao: classe abstrata */ #define ACC_SYNTHETIC 0x1000 /*!< \brief Declaracao: synthetic */ #define ACC_ENUM 0x4000 /*!< \brief Declaracao: enum*/ #define ACC_INTERFACE 0X0200 /*!< \brief Declaracao: interface*/ #define ACC_ABSTRACT 0X0400 /*!< \brief Declaracao: abstato*/ #define ACC_ANNOTATION 0X2000 /*!< \brief Declaracao: anotação*/ enum ArrayTypeCodes{ T_BOOLEAN = 4, T_CHAR, T_FLOAT, T_DOUBLE, T_BYTE, T_SHORT, T_INT , T_LONG, } arraytype_codes; /* Functions */ void classPrinter( classFile* cf); /*!< \brief Detailed description after the member */ #endif
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: mechanic.h * Author: valentino * * Created on 28 de octubre de 2020, 14:50 */ /* MODURALIZACION: Se encarga de la interfaz, entre la maquina y el usuario. FUNCIONES ------input: Esta funcion se encarga del input y de su verificacion, no recibe nada y agarra con getchar los datos ingresado por el usuario para ver si son correctos, si lo son devuelve el caracter (si es letra entonces lo devuele en minuscula) si no son validos entoces vuelve a arrancar. ------pregunta: funcion que devuelve el char correspodiente si es que se apreto si (Y) o no (N). Si ingreso uno incorrecto entonces vuelve a preguntar. No devuelve nada. ------bienvenida: funcion que le da la bienvenida al usuario */ #ifndef MECHANIC_H #define MECHANIC_H #include <stdio.h> #include <stdint.h> #define ASCII 48 #define TRUE 1 #define FALSE 0 void print_portA(unsigned int); //funcion que imprime el estado del puerto A. No devuelve nada, resive el valor del puerto A void bienvenida(); //funcion que le da la bienvenida al usuario void sw (char); //Esta funicon recibe que boton se apreto y no devuelve nada. Se encarga de cambiar los estados de los leds segun indique el usuario #endif //INPUT_H
C
#include <stdlib.h> #include <stdio.h> /* * bsearch - binary search an array of elements * @key: pointer to item being searched for * @base: pointer to first element to search * @num: number of elements * @size: size of each element * @cmp: pointer to comparison function * * This function does a binary search on the given array. The * contents of the array should already be in ascending sorted order * under the provided comparison function. * * Note that the key need not have the same type as the elements in * the array, e.g. key could be a string and the comparison function * could compare the string with the struct's name field. However, if * the key and elements in the array are of the same type, you can use * the same comparison function for both sort() and bsearch(). */ void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*cmp)(const void *key, const void *elt)) { size_t start = 0, end = num; int result; while (start < end) { size_t mid = start + (end - start) / 2; result = cmp(key, base + mid * size); if (result < 0) end = mid; else if (result > 0) start = mid + 1; else return (void *)base + mid * size; } return NULL; } int compare(const void *key, const void *elt){ int *a = (int *)key; int *b = (int *)elt; if(*a < *b){ return -1; }else if( *a > *b){ return 1; } return 0; } int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; int size = sizeof(arr)/sizeof(arr[0]); int key = 21; int *target = (int *)bsearch((void *)&key, (void *)arr, size, sizeof(int), compare); if(target != NULL){ printf("find target : %d\n", *target); }else{ printf("cannot find the target: %d!\n", key); } int key1 = 7; int *target1 = (int *)bsearch((void *)&key1, (void *)arr, size, sizeof(int), compare); if(target1 != NULL){ printf("find target1 : %d\n", *target1); }else{ printf("cannot find the target1: %d!\n", key1); } return 0; }
C
#include <stdio.h> #include "Beer.h" int menu() { int nSelection; printf("Options:\n"); printf("1) Add new beer\n"); printf("2) See all beers\n"); printf("3) Stop program\n"); printf("4) Fjern sager!\n"); scanf("%d",&nSelection); return nSelection; } int main() { struct Beer *beer; int nSelection=0; beer=NULL; while (nSelection!=3) { nSelection=menu(); if (nSelection==1) beer=addBeer(beer); else if (nSelection==2) seeBeers(beer); else if (nSelection==4){ // removeSpecificBeer(beer); beer=removeSpecificBeer2(beer); //FUCKIT(beer); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #define _FILE_OFFSET_BITS 64 #include "graph.h" int main(int argc, char *argv[]) { char* filename = argv[1]; Graph g = graph_create(1); unsigned int siz = (sizeof filename) / (sizeof *filename); if (filename[5] == 'd') g = graph_loader_directed(filename); else if (filename[5] == 'u') g = graph_loader_undirected(filename); else { printf("%d",siz); printf(" --------------- "); printf("File name must start with 'u' for undirected graph or 'd' for directed graph"); return 0; } //Graph g = graph_loader_undirected("u_Email-Enron.txt"); printf("Average path distance: %lf\n", average_path_distance(g)); printf("Network diameter: %d\n", network_diameter_optimized(g)); printf("Globale efficiency: %lf\n", globale_efficiency(g)); printf("Clustering coefficient at vertex 3: %lf\n", clustering_coefficient(g, 3)); printf("Transitivity: %lf\n", transitivity(g)); printf("Betweenness of vertex 3: %lf\n", betweenness_centrality(g, 3)); printf("Closeness of vertex 3: %lf\n", closeness_centrality(g, 3)); printf("Degree Distribution of vertex 3: %lf\n", degree_distribution(g, 3)); printf("Pearson correlation coefficient: %lf\n", pearson_correlation_coefficient(g)); }
C
#include<stdio.h> void main() { char n; printf("enter any alphabet"); scanf("%c",&n); if(n=='a'||n=='e'||n=='i'||n=='o'||n=='u'||n=='A'||n=='E'||n=='I'||n=='O'||n=='U') printf("Vowel"); else printf("Constant"); }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int Num1, Num2,TmpNum; /* ŧi3Ӿܼ */ printf("DӾƪ̤j](g.c.d):\n"); printf("пJӾ:"); scanf("%d %d",&Num1,&Num2); /* JӾ */ if (Num1 < Num2) { TmpNum=Num1; Num1=Num2; Num2=TmpNum; /* XƸj */ } while (Num2 != 0) { TmpNum=Num1 % Num2; /* Dƪlƭ */ Num1=Num2; Num2=TmpNum; /*۰k */ } printf("̤j](g.c.d)=%d\n",Num1); return 0; }
C
#include <stdio.h> #include <math.h> #include "../cephes.h" #undef fabs #include "misc.h" /* Inverse of the (regularised) incomplete Gamma integral. Given a, find x such that igam(a, x) = y. For y not small, we just use igami(a, 1-y) (inverse of the complemented incomplete Gamma integral). For y small, however, 1-y is about 1, and we lose digits. */ extern double MACHEP; static double gammainc(double x, double params[2]) { return cephes_igam(params[0], x) - params[1]; } double gammaincinv(double a, double y) { double lo = 0.0, hi; double flo = -y, fhi = 0.25 - y; double params[2]; double best_x, best_f; fsolve_result_t r; if (a <= 0.0 || y <= 0.0 || y > 0.25) { return cephes_igami(a, 1-y); } params[0] = a; params[1] = y; hi = cephes_igami(a, 0.75); /* I found Newton to be unreliable. Also, after we generate a small interval by bisection above, false position will do a large step from an interval of width ~1e-4 to ~1e-14 in one step (a=10, x=0.05, but similiar for other values). */ r = false_position(&lo, &flo, &hi, &fhi, (objective_function)gammainc, params, MACHEP, MACHEP, 1e-2*a, &best_x, &best_f); if (r == FSOLVE_NOT_BRACKET) { best_x = 0.0; } return best_x; }
C
#include<stdio.h> #include<stdlib.h> struct Process{ int bt; int order; char id[10]; int wt; int tat; }; void findWaitingTime(struct Process a[],int n){ a[0].wt=0; int i; for(i=1;i<n;i++){ a[i].wt = a[i-1].bt +a[i-1].wt; } } void findTurnAroundTime(struct Process a[],int n){ int i; for(i=0;i<n;i++){ a[i].tat = a[i].bt + a[i].wt; } } void findavgTime(struct Process a[],int n){ float total_wt=0,total_tat=0; findWaitingTime(a,n); findTurnAroundTime(a,n); printf("Processes \t Brust Time \t Waiting Time \t TurnAround Time \t \n"); int i; for(i=0;i<n;i++){ total_wt+=a[i].wt; total_tat +=a[i].tat; printf(" %s \t\t %d \t\t %d \t\t %d \n",a[i].id,a[i].bt,a[i].wt,a[i].tat); } printf("Average time : %f \n",(float)total_wt/(float)n); printf("Average turn around time : %f \n",(float)total_tat/(float)n); } int main(){ int n; printf("Enter number of process :\n"); scanf("%d",&n); struct Process a[2000]; int i; for(i=0;i<n;i++){ printf("Enter enter process id:\n"); scanf("%s",a[i].id); printf("Enter value of bt :\n"); scanf("%d",&a[i].bt); printf("Enter The value order :\n"); scanf("%d",&a[i].order); } int j; for(i=0;i<n-1;i++){ for(j=0;j<n-i-1;j++){ if(a[j+1].order <a[j].order){ struct Process t= a[j]; a[j]=a[j+1]; a[j+1]=t; } } } findavgTime(a,n); return 0; }
C
#include <stdio.h> int main() { float argent; printf("argent ? "); scanf("%f", &argent); int moyen[15] = {50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1}; int r = argent * 100, n; for(int i = 0; i < 15; i++) { n = r / moyen[i]; if(n != 0) { if(moyen[i] < 100) printf("Pieces de %dc : %d\n", moyen[i], n); else printf("Billets de %d : %d\n", moyen[i] / 100, n); } r %= moyen[i]; } return(0); }
C
//2 #include<stdio.h> #include<stdlib.h> #pragma warning(disable : 4996) int number, nownum, n, numl, vv[3];//number: ,n: ,numl:ʱ Է¹ number nownum = 0; typedef struct disjoint//и ڵ { int size; struct node *head; struct node *tail; }disjoint; disjoint *sack; typedef struct Que { int u; int v; int weight; }Q; typedef struct node { struct node *next; int element; struct node *set;//Ҽ }node; typedef struct enode { int endpoints[2]; int weight; }enode; node *vertices; enode *edges; void changeweight(int a, int b, int n, int w) { enode *temp; int i, out, ai, bi, change, interi, outeri; ai = a, bi = b; if (ai > bi) { change = bi; bi = ai; ai = change; } nownum++;//Ȯ ũ i = 0; for (i = 0; i <= nownum - 2; i++) { if ((edges + i)->endpoints[0] > ai) break; if ((edges + i)->endpoints[0] == ai) { if ((edges + (i + 1))->endpoints[0] > ai) { if ((edges + i)->endpoints[1] <= bi) { i++; break; } } else if ((edges + (i + 1))->endpoints[0] == ai) { if ((edges + i)->endpoints[1] <= bi && (edges + (i + 1))->endpoints[1] >= bi) { i++; break; } if ((edges + i)->endpoints[1] > bi) break; } } if ((edges + i)->endpoints[0] < ai) { if ((edges + (i + 1))->endpoints[0] > ai) { i++; break; } else if ((edges + (i + 1))->endpoints[0] == ai) { if ((edges + (i + 1))->endpoints[1] >= bi) { i++; break; } } } } interi = i;//e temp = (enode*)malloc(sizeof(enode) * number); for (i = 0; i < interi; i++) { (temp + i)->weight = (edges + i)->weight; (temp + i)->endpoints[0] = (edges + i)->endpoints[0]; (temp + i)->endpoints[1] = (edges + i)->endpoints[1]; } (temp + interi)->weight = w; (temp + interi)->endpoints[0] = ai; (temp + interi)->endpoints[1] = bi; for (i = interi + 1; i < nownum; i++) { (temp + i)->weight = (edges + (i - 1))->weight; (temp + i)->endpoints[0] = (edges + (i - 1))->endpoints[0]; (temp + i)->endpoints[1] = (edges + (i - 1))->endpoints[1]; } free(edges); edges = temp; return; } void swap(Q *H, int a, int b) //ȯ { int utemp, vtemp, wtemp; utemp = (H + a)->u; vtemp = (H + a)->v; wtemp = (H + a)->weight; (H + a)->u = (H + b)->u; (H + a)->v = (H + b)->v; (H + a)->weight = (H + b)->weight; (H + b)->u = utemp; (H + b)->v = vtemp; (H + b)->weight = wtemp; } void downHeap(Q *H, int i) //ڽ 峢 ڽŰ ϰų ڽ ̹ { int min; //min if (i * 2 <= number) { min = i * 2; if (i * 2 + 1 <= number) { if ((H + (i * 2 + 1))->weight < (H + (min))->weight)//켱 ť Ը min = i * 2 + 1; } if ((H + i)->weight > (H + min)->weight) { swap(H, i, min); downHeap(H, min); } } } void printtree(Q *mst) { int i, sum; i = 1, sum = 0; for (int k = 1; k < n; k++) { printf(" %d", (mst + k)->weight); } while (i < n) { sum += (mst + i)->weight; i++; } printf("\n"); printf("%d", sum); } void rBuildHeap(Q *H, int i) // { if (i <= number) { rBuildHeap(H, 2 * i); rBuildHeap(H, 2 * i + 1); downHeap(H, i); } } void removemin(Q *H) { vv[0] = (H + 1)->u;//vv 켱 ť ּ vv[1] = (H + 1)->v; vv[2] = (H + 1)->weight; swap(H, 1, number); number--; rBuildHeap(H, 1); } void unionsack()//賶 պ { int i, j; for (i = 0; i < n; i++)//ش(vv[0]) ִ и ε ϱ { if ((sack + i)->head == (vertices + vv[0])->set) break; } for (j = 0; j < n; j++)//ش(vv[1]) ִ и ε ϱ { if ((sack + j)->head == (vertices + vv[1])->set) break; } if ((sack + i)->size <= (sack + j)->size)//ũⰡ ūͿ պŰ { node *temp; temp = (sack + i)->head; if (temp != NULL) (sack + j)->tail->next = temp; while (temp != NULL) { if (temp->next == NULL) (sack + j)->tail = temp; temp->set = (sack + j)->head; temp = temp->next; } (sack + i)->head = NULL; (sack + i)->tail = NULL; (sack + j)->size += (sack + i)->size; (sack + i)->size = 0; } else { node *temp; temp = (sack + j)->head; if (temp != NULL) (sack + i)->tail->next = temp; while (temp != NULL) { if (temp->next == NULL) (sack + i)->tail = temp; temp->set = (sack + i)->head; temp = temp->next; } (sack + j)->head = NULL; (sack + j)->tail = NULL; (sack + i)->size += (sack + j)->size; (sack + j)->size = 0; } } void kruskalmst(Q *H, Q *mst) { int n1, n2; for (int i = 0; i < n; i++) { (vertices + i)->next = NULL; (sack + i)->size = 1; (sack + i)->head = (vertices + i); (sack + i)->tail = (vertices + i); (vertices + i)->set = (sack + i)->head; } for (int i = 0; i < number; i++)//켱 ť ־ { (H + (i + 1))->u = (edges + i)->endpoints[0]; (H + (i + 1))->v = (edges + i)->endpoints[1]; (H + (i + 1))->weight = (edges + i)->weight; } rBuildHeap(H, 1); while (number >= 1) { removemin(H);//Q u,v if ((vertices + vv[0])->set != (vertices + vv[1])->set)// 賶ȿ ʴٸ { (mst + (numl - number))->u = vv[0];//mstƮ (mst + (numl - number))->v = vv[1]; (mst + (numl - number))->weight = vv[2]; unionsack();//պ } else numl--; } } int main() { char input; int a, b, w, nn, mm; Q *H, *mst; scanf("%d %d", &n, &number); numl = number;//number ص sack = (disjoint*)malloc(sizeof(disjoint)*n);//sack n H = (Q*)malloc(sizeof(Q)*(number + 1)); mst = (Q*)malloc(sizeof(Q)*n);//n-1 vertices = (node*)malloc(sizeof(node) * n); edges = (enode*)malloc(sizeof(enode) * number); for (int i = 0; i < n; i++) { (vertices + i)->element = i + 1; } for (int i = 0; i < number; i++) { (edges + i)->endpoints[0] = -1; (edges + i)->endpoints[1] = -1; } for (int i = 0; i < number; i++) { scanf("%d %d %d", &nn, &mm, &w); changeweight(nn - 1, mm - 1, n, w); } kruskalmst(H, mst); printtree(mst); return 0; }
C
#ifndef ME_UTIL_H #define ME_UTIL_H color meDesaturate ( color in_color; float dsat ) { float lum = .2125*comp(in_color, 0) + .7154*comp(in_color, 1) + .0721*comp(in_color, 2); color out_color = mix(color(lum), in_color, dsat); return out_color; } color meCmix(color a; color b; color mixture) { return (1 - mixture) * a + mixture * b; } normal meShadingNormal( normal n ) { extern vector I; normal Nn = normalize( n ); normal Nf = faceforward( Nn, I, Nn ); normal Ns = normalize( Nf ); /* shading normal */ return Ns; } /* * Build a set of four vectors around a center vector * This is necessary for making environment calls inside * of a gather loop. If we just used a single vector, * we would get derivative information based on neighboring * grids, which is not what we want. Instead, we want to * do a lookup on a patch of the environment that is inversely * related to the number of samples we are using. * * spread is the halfwidth of the patch we are using * * This is calculated as a separate function so that it can be * called outside of the gather loop (for the sake of optimization). */ float meCalculateEnvSampleArea( float hemisphere; float numSamples; ) { return 0.5 * (hemisphere / numSamples); } void meBuildEnvironmentVectors( float spread; vector dir; output vector v1; output vector v2; output vector v3; output vector v4; ) { vector udir, vdir, wdir; // construct basis vectors if (abs(xcomp(dir)) > 0 || abs(ycomp(dir)) > 0) // dir ^ z (if valid) udir = normalize(vector (ycomp(dir), -xcomp(dir), 0)); else // dir ^ x udir = normalize(vector (0, zcomp(dir), -ycomp(dir))); // vdir is dir ^ u vdir = normalize(dir ^ udir); // calculate four directions vector uspread = spread*udir; vector vspread = spread*vdir; vector ndir = normalize(dir); v1 = ndir - uspread - vspread; v2 = ndir + uspread - vspread; v3 = ndir - uspread + vspread; v4 = ndir + uspread + vspread; } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fork.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: qdiaz <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/04/19 11:56:17 by qdiaz #+# #+# */ /* Updated: 2016/04/19 11:56:18 by qdiaz ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" char **path_in_tab(t_env *env, char **cmd) { char **path_tab; int nb_dir; char *bin_path; nb_dir = 0; path_tab = NULL; bin_path = ft_getbin_path(cmd[0]); while (env) { if (ft_strcmp(env->name, "PATH") == 0 && bin_path == NULL) path_tab = ft_strsplit(env->content, ':'); env = env->next; } if (!path_tab) { if ((path_tab = (char **)malloc(sizeof(char *) * 2))) { path_tab[0] = ft_getbin_path(cmd[0]); path_tab[1] = NULL; } else return (NULL); } ft_strdel(&bin_path); return (path_tab); } static char *search_path(char **path_tab, char **cmd) { char *tmp; char *tmp2; int i; i = -1; tmp = NULL; tmp2 = ft_getbin_name(cmd[0]); if (!path_tab) return (NULL); return (search_path2(tmp2, tmp, path_tab, i)); } int exe_fork2(char **cmd, char **path_tab) { pid_t pid; char *cmd_path; if ((cmd_path = search_path(path_tab, cmd)) == NULL) { ft_env_error(cmd[0]); free_tab(path_tab); return (-1); } pid = fork(); if (pid > 0) wait(0); else if (pid == 0) { signal(SIGINT, SIG_DFL); if (cmd[0][ft_strlen(cmd[0])] != '/') cmd_path = ft_strjoin(cmd_path, "/"); cmd_path = ft_strjoin(cmd_path, ft_getbin_name(cmd[0])); if (env_manage_error(cmd_path) != -1) execve(cmd_path, cmd, NULL); } ft_strdel(&cmd_path); free_tab(path_tab); return (0); } int exe_fork(t_env *env, char **cmd, char **path_tab) { pid_t pid; char *cmd_path; char **env_cpy; if ((cmd_path = search_path(path_tab, cmd)) == NULL) { fork_error(cmd, path_tab); return (-1); } env_cpy = list_in_tab(env); pid = fork(); if (pid > 0) wait(0); else if (pid == 0) { signal(SIGINT, SIG_DFL); if (cmd[0][ft_strlen(cmd[0])] != '/') cmd_path = ft_strjoin(cmd_path, "/"); cmd_path = ft_strjoin(cmd_path, ft_getbin_name(cmd[0])); execve(cmd_path, cmd, env_cpy); } free_tab(env_cpy); ft_strdel(&cmd_path); free_tab(path_tab); return (0); }
C
#pragma once #include "math/linalg/vec.h" #include "math/rotation.h" struct TranslationalMotion { Vec3 velocity; Vec3 acceleration; inline TranslationalMotion() : velocity(0.0, 0.0, 0.0), acceleration(0.0, 0.0, 0.0) {} inline TranslationalMotion(Vec3 velocity) : velocity(velocity), acceleration(0.0, 0.0, 0.0) {} inline TranslationalMotion(Vec3 velocity, Vec3 acceleration) : velocity(velocity), acceleration(acceleration) {} inline Vec3 getOffsetAfterDeltaT(double deltaT) const { return velocity * deltaT + acceleration * deltaT * deltaT / 2; } inline TranslationalMotion operator-() const { return TranslationalMotion(-velocity, -acceleration); } }; inline TranslationalMotion operator+(const TranslationalMotion& first, const TranslationalMotion& second) { return TranslationalMotion(first.velocity + second.velocity, first.acceleration + second.acceleration); } inline TranslationalMotion& operator+=(TranslationalMotion& first, const TranslationalMotion& second) { first.velocity += second.velocity; first.acceleration += second.acceleration; return first; } inline TranslationalMotion operator*(const TranslationalMotion& motion, double factor) { return TranslationalMotion(motion.velocity * factor, motion.acceleration * factor); } inline TranslationalMotion operator*(double factor, const TranslationalMotion& motion) { return motion * factor; } struct RotationalMotion { Vec3 angularVelocity; Vec3 angularAcceleration; inline RotationalMotion() : angularVelocity(0.0,0.0,0.0), angularAcceleration(0.0,0.0,0.0) {} inline RotationalMotion(Vec3 angularVelocity) : angularVelocity(angularVelocity), angularAcceleration(0.0, 0.0, 0.0) {} inline RotationalMotion(Vec3 angularVelocity, Vec3 angularAcceleration) : angularVelocity(angularVelocity), angularAcceleration(angularAcceleration) {} inline Vec3 getVelocityOfPoint(Vec3 relativePoint) const { return angularVelocity % relativePoint; } inline Vec3 getAccelerationOfPoint(Vec3 relativePoint) const { return angularAcceleration % relativePoint + angularVelocity % (angularVelocity % relativePoint); } inline TranslationalMotion getTranslationalMotionOfPoint(Vec3 relativePoint) const { return TranslationalMotion(getVelocityOfPoint(relativePoint), getAccelerationOfPoint(relativePoint)); } inline Vec3 getRotationAfterDeltaT(double deltaT) const { return angularVelocity * deltaT + angularAcceleration * deltaT * deltaT / 2; } }; inline RotationalMotion operator*(const RotationalMotion& motion, double factor) { return RotationalMotion(motion.angularVelocity * factor, motion.angularAcceleration * factor); } inline RotationalMotion operator*(double factor, const RotationalMotion& motion) { return motion * factor; } struct Movement { Vec3 translation; Vec3 rotation; }; struct Motion { TranslationalMotion translation; RotationalMotion rotation; inline Motion() = default; inline Motion(Vec3 velocity, Vec3 angularVelocity) : translation(velocity), rotation(angularVelocity) {} inline Motion(Vec3 velocity, Vec3 angularVelocity, Vec3 acceleration, Vec3 angularAcceleration) : translation(velocity, acceleration), rotation(angularVelocity, angularAcceleration) {} inline Motion(TranslationalMotion translationMotion, RotationalMotion rotationMotion) : translation(translationMotion), rotation(rotationMotion) {} inline Vec3 getVelocityOfPoint(Vec3 relativePoint) const { return translation.velocity + rotation.getVelocityOfPoint(relativePoint); } inline Vec3 getAccelerationOfPoint(Vec3 relativePoint) const { return translation.acceleration + rotation.getAccelerationOfPoint(relativePoint); } inline TranslationalMotion getTranslationalMotionOfPoint(Vec3 relativePoint) const { return translation + rotation.getTranslationalMotionOfPoint(relativePoint); } inline Motion getMotionOfPoint(Vec3 relativePoint) const { return Motion( getTranslationalMotionOfPoint(relativePoint), rotation ); } inline Motion addRelativeMotion(const Motion& relativeMotion) const { return Motion( translation.velocity + relativeMotion.translation.velocity, rotation.angularVelocity + relativeMotion.rotation.angularVelocity, translation.acceleration + relativeMotion.translation.acceleration + rotation.angularVelocity % relativeMotion.translation.velocity * 2, rotation.angularAcceleration + relativeMotion.rotation.angularAcceleration + rotation.angularVelocity % relativeMotion.rotation.angularVelocity ); } inline Motion addOffsetRelativeMotion(Vec3 offset, const Motion& relativeMotion) const { return this->getMotionOfPoint(offset).addRelativeMotion(relativeMotion); } inline Movement getMovementAfterDeltaT(double deltaT) const { return Movement{translation.getOffsetAfterDeltaT(deltaT), rotation.getRotationAfterDeltaT(deltaT)}; } }; inline Motion operator+(const TranslationalMotion& motionOfStart, const Motion& motionToTranslate) { return Motion(motionOfStart + motionToTranslate.translation, motionToTranslate.rotation); } inline TranslationalMotion localToGlobal(const Rotation& rot, const TranslationalMotion& motion) { return TranslationalMotion(rot.localToGlobal(motion.velocity), rot.localToGlobal(motion.acceleration)); } inline TranslationalMotion globalToLocal(const Rotation& rot, const TranslationalMotion& motion) { return TranslationalMotion(rot.globalToLocal(motion.velocity), rot.globalToLocal(motion.acceleration)); } inline RotationalMotion localToGlobal(const Rotation& rot, const RotationalMotion& motion) { return RotationalMotion(rot.localToGlobal(motion.angularVelocity), rot.localToGlobal(motion.angularAcceleration)); } inline RotationalMotion globalToLocal(const Rotation& rot, const RotationalMotion& motion) { return RotationalMotion(rot.globalToLocal(motion.angularVelocity), rot.globalToLocal(motion.angularAcceleration)); } inline Motion localToGlobal(const Rotation& rot, const Motion& motion) { return Motion(localToGlobal(rot, motion.translation), localToGlobal(rot, motion.rotation)); } inline Motion globalToLocal(const Rotation& rot, const Motion& motion) { return Motion(globalToLocal(rot, motion.translation), globalToLocal(rot, motion.rotation)); }
C
#include "io.h" #include <unistd.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <netdb.h> #include <errno.h> // io connect static int io_connect(const char *ip, const short port, int family, int type); int io_tcp_connect(const char *ip, const short port) { return io_connect(ip, port, AF_INET, SOCK_STREAM); } int io_udp_connect(const char *ip, const short port) { return io_connect(ip, port, AF_INET, SOCK_DGRAM); } int io_tcp_listen(const char *host, const char *serv) { // int listenfd, n; const int on = 1; struct addrinfo hints, *res, *ressave; bzero(&hints, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (getaddrinfo(host, serv, &hints, &res) != 0) { fprintf(stderr, "%s:%d getaddrinfo<%s, %s> error: %s\n", __FILE__, __LINE__, host, serv, strerror(errno)); return -1; } ressave = res; do { listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (listenfd < 0) continue ; setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0) break ; close(listenfd); } while ((res = res->ai_next) != NULL); if (res == NULL) { fprintf(stderr, "%s:%d listen error for %s, %s\n", __FILE__, __LINE__, host, serv); exit(0); } if (listen(listenfd, 0) < 0) { fprintf(stderr, "%s:%d listen error for %s, %s, error: %s", __FILE__, __LINE__, host, serv, strerror(errno)); exit(0); } freeaddrinfo(ressave); return listenfd; } // io connect static int io_connect(const char *ip, const short port, int family, int type) { int sockfd; struct addrinfo hints, *res, *ressave; bzero(&hints, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = type; char port_str[20]; bzero(port_str, 20); sprintf(port_str, "%d", port); if (getaddrinfo(ip, port_str, &hints, &res) != 0) { fprintf(stderr, "%s:%d getaddrinfo<%s, %d> error: %s\n", __FILE__, __LINE__, ip, port, strerror(errno)); return -1; } ressave = res; do { // printf("protocol: %d\n", res->ai_protocol); if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) { fprintf(stderr, "%s:%d socket error: %s\n", __FILE__, __LINE__, strerror(errno)); continue; } if (connect(sockfd, res->ai_addr, res->ai_addrlen) < 0) { fprintf(stderr, "%s:%d connect ip<%s> error: %s\n", __FILE__, __LINE__, ip, strerror(errno)); } else { // printf("sockfd: %d\n", sockfd); return sockfd; } if (close(sockfd) < 0) { fprintf(stderr, "%s:%d close error: %s\n", __FILE__, __LINE__, strerror(errno)); } } while ((res = res->ai_next) != NULL); freeaddrinfo(ressave); return -1; } // io reand and write line ssize_t io_readn(int fd, void *vptr, size_t n) { size_t nleft; ssize_t nread; char *ptr; ptr = vptr; nleft = n; while(nleft > 0) { if((nread = read(fd, ptr, nleft)) < 0) { if(errno == EINTR) nread = 0; /* and call read() again */ else return -1; }else if(nread == 0) break; /* EOF */ nleft -= nread; ptr += nread; } return n - nleft; /* return >= 0 */ } ssize_t io_writen(int fd, const void *vptr, size_t n) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = vptr; nleft = n; while(nleft > 0) { if((nwritten = write(fd, ptr, nleft)) < 0) { if(nwritten < 0 && errno == EINTR) nwritten = 0; /* and call write() again */ else return -1; } nleft -= nwritten; ptr += nwritten; } return n; } ssize_t io_readline(int fd, void *vptr, size_t maxlen) { ssize_t n, rc; char c, *ptr; ptr = vptr; for(n = 1; n < maxlen; n++) { again: if((rc = read(fd, &c, 1)) == 1) { *ptr++ = c; if(c == '\n') break; /* newline is stored, like fgets() */ } else if (rc == 0) { *ptr = 0; return n - 1; /* EOF, n -1 bytes were read */ } else { if (errno == EINTR) goto again; return -1; /* error, errno set by read() */ } } *ptr = 0; return n; }
C
// three_func.c -- 一個文件中包含2個函數 #include <stdio.h> void br(void); // 函數原型 void ic(void); int main(void) { br(); // 函數調用 ic(); printf("India, China,\n"); printf("Brazil, Russia\n"); return 0; } void br(void) // 函數定義 { printf("Brazil, Russia, "); } void ic(void) { printf("India, China\n"); }