repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
NightfallDM/xbook2
src/arch/x86/mach-i386/gate.c
#include <arch/segment.h> #include <arch/gate.h> #include <arch/interrupt.h> #include <arch/pic.h> #include <arch/registers.h> #include <xbook/kernel.h> /* * Interrupt descriptor table */ struct gate_descriptor *idt; // 总共支持的中断数 #define MAX_IDT_NR (IDT_LIMIT/8) /* 用户消息int软中断号,用于从用户态切换到内核态执行操作 */ #define KERN_USRMSG_NR 0x40 extern void exception_entry0x00(); extern void exception_entry0x01(); extern void exception_entry0x02(); extern void exception_entry0x03(); extern void exception_entry0x04(); extern void exception_entry0x05(); extern void exception_entry0x06(); extern void exception_entry0x07(); extern void exception_entry0x08(); extern void exception_entry0x09(); extern void exception_entry0x0a(); extern void exception_entry0x0b(); extern void exception_entry0x0c(); extern void exception_entry0x0d(); extern void exception_entry0x0e(); extern void exception_entry0x0f(); extern void exception_entry0x10(); extern void exception_entry0x11(); extern void exception_entry0x12(); extern void exception_entry0x13(); extern void exception_entry0x14(); extern void exception_entry0x15(); extern void exception_entry0x16(); extern void exception_entry0x17(); extern void exception_entry0x18(); extern void exception_entry0x19(); extern void exception_entry0x1a(); extern void exception_entry0x1b(); extern void exception_entry0x1c(); extern void exception_entry0x1d(); extern void exception_entry0x1e(); extern void exception_entry0x1f(); extern void irq_entry0x20(); extern void irq_entry0x21(); extern void irq_entry0x22(); extern void irq_entry0x23(); extern void irq_entry0x24(); extern void irq_entry0x25(); extern void irq_entry0x26(); extern void irq_entry0x27(); extern void irq_entry0x28(); extern void irq_entry0x29(); extern void irq_entry0x2a(); extern void irq_entry0x2b(); extern void irq_entry0x2c(); extern void irq_entry0x2d(); extern void irq_entry0x2e(); extern void irq_entry0x2f(); extern void syscall_handler(); static void set_gate_descriptor(struct gate_descriptor *descriptor, intr_handler_t offset, unsigned int selector, unsigned int attributes, unsigned char privilege) { descriptor->offset_low = (unsigned int)offset & 0xffff; descriptor->selector = selector; descriptor->attributes = attributes | (privilege << 5); descriptor->datacount = 0; descriptor->offset_high = ((unsigned int)offset >> 16) & 0xffff; } static void init_interrupt_descriptor() { idt = (struct gate_descriptor *) IDT_VADDR; /* 将中断描述符表的内容设置成内核下的中断门 并把汇编部分的中断处理函数传入进去 */ int i; for (i = 0; i < MAX_IDT_NR; i++) { set_gate_descriptor(&idt[i], 0, 0, 0, 0); } /* 异常的中断入口 */ set_gate_descriptor(&idt[0x00], exception_entry0x00, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x01], exception_entry0x01, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x02], exception_entry0x02, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x03], exception_entry0x03, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x04], exception_entry0x04, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x05], exception_entry0x05, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x06], exception_entry0x06, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x07], exception_entry0x07, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x08], exception_entry0x08, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x09], exception_entry0x09, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x0a], exception_entry0x0a, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x0b], exception_entry0x0b, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x0c], exception_entry0x0c, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x0d], exception_entry0x0d, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x0e], exception_entry0x0e, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x0f], exception_entry0x0f, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x10], exception_entry0x10, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x11], exception_entry0x11, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x12], exception_entry0x12, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x13], exception_entry0x13, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x14], exception_entry0x14, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x15], exception_entry0x15, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x16], exception_entry0x16, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x17], exception_entry0x17, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x18], exception_entry0x18, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x19], exception_entry0x19, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x1a], exception_entry0x1a, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x1b], exception_entry0x1b, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x1c], exception_entry0x1c, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x1d], exception_entry0x1d, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x1e], exception_entry0x1e, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x1f], exception_entry0x1f, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); /* IRQ的中断入口 */ set_gate_descriptor(&idt[0x20], irq_entry0x20, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x21], irq_entry0x21, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x22], irq_entry0x22, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x23], irq_entry0x23, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x24], irq_entry0x24, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x25], irq_entry0x25, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x26], irq_entry0x26, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x27], irq_entry0x27, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x28], irq_entry0x28, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x29], irq_entry0x29, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x2a], irq_entry0x2a, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x2b], irq_entry0x2b, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x2c], irq_entry0x2c, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x2d], irq_entry0x2d, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x2e], irq_entry0x2e, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); set_gate_descriptor(&idt[0x2f], irq_entry0x2f, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL0); /* 系统调用处理中断 */ set_gate_descriptor(&idt[KERN_USRMSG_NR], syscall_handler, KERNEL_CODE_SEL, DA_386IGate, DA_GATE_DPL3); load_idtr(IDT_LIMIT, IDT_VADDR); } void init_gate_descriptor() { /* interrupt gate */ init_interrupt_descriptor(); /* intr expection setting */ init_intr_expection(); }
NightfallDM/xbook2
library/xlibc/include/arch/x86/atomic.h
<reponame>NightfallDM/xbook2<filename>library/xlibc/include/arch/x86/atomic.h #ifndef _LIB_x86_ATOMIC_H #define _LIB_x86_ATOMIC_H /* 定义出口 */ void __atomic_add(int *a, int b); void __atomic_sub(int *a, int b); void __atomic_inc(int *a); void __atomic_dec(int *a); void __atomic_or(int *a, int b); void __atomic_and(int *a, int b); #endif /* _LIB_x86_ATOMIC_H */
NightfallDM/xbook2
src/arch/x86/include/arch/cpu.h
<reponame>NightfallDM/xbook2<filename>src/arch/x86/include/arch/cpu.h #ifndef _ARCH_CPU_H #define _ARCH_CPU_H #define cpu_lazy __cpu_lazy #define cpu_idle __cpu_idle static inline void arch_cpu_pause(void) { __asm__ __volatile__ ("pause"); } static inline void get_cpuid(unsigned int Mop,unsigned int Sop,unsigned int * a,unsigned int * b,unsigned int * c,unsigned int * d) { __asm__ __volatile__ ( "cpuid \n\t" :"=a"(*a),"=b"(*b),"=c"(*c),"=d"(*d) :"0"(Mop),"2"(Sop) ); } #endif /* _ARCH_CPU_H */
NightfallDM/xbook2
library/xlibc/math/fmod.c
<filename>library/xlibc/math/fmod.c /* File: fmod.c Contains: For x % y in float Written by: GUI Copyright: (C) 2017-2020 by GuEe Studio for Book OS. All rights reserved. */ #include <math.h> M_FLOAT fmod(M_FLOAT x, M_FLOAT y) { return (x - (int)(x / y) * y); }
NightfallDM/xbook2
src/net/net.c
<filename>src/net/net.c #include <xbook/netcard.h> #include <xbook/net.h> #include <xbook/clock.h> #include <xbook/task.h> #include <xbook/schedule.h> #include <lwip/netif.h> #include <lwip/ip.h> #include <lwip/tcp.h> #include <lwip/init.h> #include <netif/etharp.h> #include <lwip/timers.h> #include <lwip/udp.h> #include <lwip/tcpip.h> extern err_t ethernetif_init(struct netif *netif); extern void ethernetif_input(struct netif *netif); struct netif rtl8139_netif; void httpserver_init(); void socket_examples_init(void); /** * 0: 仅虚拟机和主机通信 * 1: 虚拟机和主机以及外网通信 * 2: DHCP动态分配ip */ #define CONFIG_LEVEL 0 void lwip_init_task(void) { struct ip_addr ipaddr, netmask, gateway; #if NO_SYS == 1 lwip_init(); #else tcpip_init(NULL, NULL); #endif #if CONFIG_LEVEL == 0 IP4_ADDR(&ipaddr, 192,168,0,105); IP4_ADDR(&gateway, 192,168,0,1); IP4_ADDR(&netmask, 255,255,0, 0); #elif CONFIG_LEVEL == 1 IP4_ADDR(&gateway, 169,254,177,48); IP4_ADDR(&netmask, 255,255,0,0); IP4_ADDR(&ipaddr, 169,254,177,105); #elif CONFIG_LEVEL == 2 IP4_ADDR(&gateway, 0,0,0,0); IP4_ADDR(&netmask, 0,0,0,0); IP4_ADDR(&ipaddr, 0,0,0,0); #endif #if NO_SYS == 1 netif_add(&rtl8139_netif, &ipaddr, &netmask, &gateway, NULL, ethernetif_init, ethernet_input); #else netif_add(&rtl8139_netif, &ipaddr, &netmask, &gateway, NULL, ethernetif_init, tcpip_input); #endif netif_set_default(&rtl8139_netif); netif_set_up(&rtl8139_netif); #if CONFIG_LEVEL == 2 printk("[%s] %s: dhcp start.\n", SRV_NAME, __func__); dhcp_start(&rtl8139_netif); printk("[%s] %s: dhcp done.\n", SRV_NAME, __func__); #endif } /** * netin: * 网络输入线程,从网卡读取数据包,如果有数据就返回,没有数据就阻塞。 * 这样可以减轻CPU负担。 */ void netin_kthread(void *arg) { printk("[NETIN]: init start.\n"); #if 1 lwip_init_task(); httpserver_init(); //socket_examples_init(); while(1) { /* 检测输入,如果没有收到数据就会阻塞。 */ ethernetif_input(&rtl8139_netif); //todo: add your own user code here } #endif } /* 网络初始化 */ void init_net(void) { printk("[NET]: init start.\n"); if (init_netcard_driver() < 0) pr_err("init netcard driver failed!\n"); /* 打开一个线程来读取网络数据包 */ task_t * netin = kthread_start("netin", TASK_PRIO_RT, netin_kthread, NULL); if (netin == NULL) { pr_err("[NET]: start kthread netin failed!\n"); } } #if LWIP_NETCONN #ifndef HTTPD_DEBUG #define HTTPD_DEBUG LWIP_DBG_OFF #endif const static char http_html_hdr[] = "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n"; const static char http_index_html[] = "<html><head><title>Congrats!</title></head><body><h1>Welcome to LwIP 1.4.1 HTTP server!</h1> \ <center><p>This is a test page based on netconn API.</center></body></html>"; /** Serve one HTTP connection accepted in the http thread */ static void httpserver_serve(struct netconn *conn) { struct netbuf *inbuf; char *buf; u16_t buflen; err_t err; /* Read the data from the port, blocking if nothing yet there. We assume the request (the part we care about) is in one netbuf */ err = netconn_recv(conn, &inbuf); if (err == ERR_OK) { netbuf_data(inbuf, (void**)&buf, &buflen); /* Is this an HTTP GET command? (only check the first 5 chars, since there are other formats for GET, and we're keeping it very simple )*/ if (buflen>=5 && buf[0]=='G' && buf[1]=='E' && buf[2]=='T' && buf[3]==' ' && buf[4]=='/' ) { /* Send the HTML header * subtract 1 from the size, since we dont send the \0 in the string * NETCONN_NOCOPY: our data is const static, so no need to copy it */ netconn_write(conn, http_html_hdr, sizeof(http_html_hdr)-1, NETCONN_COPY); /* Send our HTML page */ netconn_write(conn, http_index_html, sizeof(http_index_html)-1, NETCONN_COPY); mdelay(10); } } /* Close the connection (server closes in HTTP) */ netconn_close(conn); /* Delete the buffer (netconn_recv gives us ownership, so we have to make sure to deallocate the buffer) */ netbuf_delete(inbuf); } /** The main function, never returns! */ static void httpserver_thread(void *arg) { struct netconn *conn, *newconn; err_t err; LWIP_UNUSED_ARG(arg); /* Create a new TCP connection handle */ conn = netconn_new(NETCONN_TCP); LWIP_ERROR("http_server: invalid conn", (conn != NULL), return;); err = netconn_bind(conn, NULL, 80); /* Bind to port 80 (HTTP) with default IP address */ if (err != ERR_OK) { pr_err("netconn_bind error %d!\n", err); spin("netconn_bind"); } /* Put the connection into LISTEN state */ if (netconn_listen(conn) != ERR_OK) { pr_err("netconn_listen error!\n"); spin("netconn_listen"); } do { err = netconn_accept(conn, &newconn); if (err == ERR_OK) { httpserver_serve(newconn); netconn_delete(newconn); } } while(err == ERR_OK); LWIP_DEBUGF(HTTPD_DEBUG, ("http_server_netconn_thread: netconn_accept received error %d, shutting down", err)); netconn_close(conn); netconn_delete(conn); } /** Initialize the HTTP server (start its thread) */ void httpserver_init() { sys_thread_new("http_server_netconn", httpserver_thread, NULL, DEFAULT_THREAD_STACKSIZE, TASK_PRIO_USER); } #endif #if LWIP_SOCKET #include "lwip/sockets.h" #include "lwip/sys.h" #include <string.h> #include <stdio.h> #ifndef SOCK_TARGET_HOST #define SOCK_TARGET_HOST "192.168.0.104" #endif #ifndef SOCK_TARGET_PORT #define SOCK_TARGET_PORT 8080 #endif char zrxbuf[1024]; /** This is an example function that tests blocking-connect and nonblocking--recv-write . */ static void socket_nonblocking(void *arg) { int s; int ret; u32_t opt; struct sockaddr_in addr; int err; LWIP_UNUSED_ARG(arg); /* set up address to connect to */ memset(&addr, 0, sizeof(addr)); addr.sin_len = sizeof(addr); addr.sin_family = AF_INET; addr.sin_port = PP_HTONS(SOCK_TARGET_PORT); addr.sin_addr.s_addr = inet_addr(SOCK_TARGET_HOST); /* create the socket */ //s = socket(AF_INET, SOCK_STREAM, 0); //LWIP_ASSERT("s >= 0", s >= 0); /* connect */ do { s = lwip_socket(AF_INET, SOCK_STREAM, 0); LWIP_ASSERT("s >= 0", s >= 0); ret = lwip_connect(s, (struct sockaddr*)&addr, sizeof(addr)); printk("socket connect result [%d]\n", ret); if(ret != 0) { lwip_close(s); } }while(ret != 0); /* should have an error: "inprogress" */ if(ret != 0) { ret = lwip_close(s); while(1) { printk("socket connect error\n"); sys_msleep(1000); } } /* nonblocking */ opt = 1; ret = lwip_ioctl(s, FIONBIO, &opt); LWIP_ASSERT("ret == 0", ret == 0); /* write should fail, too */ while(1) { ret = lwip_read(s, zrxbuf, 1024); if (ret > 0) { /* should return 0: closed */ printk("socket recv a data\n"); } printk("socket recv [%d]\n", ret); ret = lwip_write(s, "test", 4); if(ret>0) { printk("socket send %d data\n",ret); } else { ret = lwip_close(s); printk("socket closed %d\n",ret); while(1) sys_msleep(1000); } sys_msleep(1000); } } /** This is an example function that tests the recv function (timeout etc.). */ char rxbuf[1024]; char sndbuf[64]; static void socket_timeoutrecv(void *arg) { int s; int ret; int opt; struct sockaddr_in addr; size_t len; LWIP_UNUSED_ARG(arg); /* set up address to connect to */ memset(&addr, 0, sizeof(addr)); addr.sin_len = sizeof(addr); addr.sin_family = AF_INET; addr.sin_port = PP_HTONS(SOCK_TARGET_PORT); addr.sin_addr.s_addr = inet_addr(SOCK_TARGET_HOST); /* first try blocking: */ /* create the socket */ //s = socket(AF_INET, SOCK_STREAM, 0); //LWIP_ASSERT("s >= 0", s >= 0); /* connect */ do { s = lwip_socket(AF_INET, SOCK_STREAM, 0); LWIP_ASSERT("s >= 0", s >= 0); ret = lwip_connect(s, (struct sockaddr*)&addr, sizeof(addr)); printk("socket connect result [%d]\n", ret); if(ret != 0) { lwip_close(s); } }while(ret != 0); /* should succeed */ if(ret != 0) { printk("socket connect error %d\n", ret); ret = lwip_close(s); while(1) sys_msleep(1000); } /* set recv timeout (100 ms) */ opt = 100; ret = lwip_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &opt, sizeof(int)); while(1) { len = 0; ret = lwip_recv(s, zrxbuf, 1024, 0); if (ret > 0) { /* should return 0: closed */ //printk("socket recv a data\n"); len = ret; } printk("read [%d] data\n", ret); len = sprintf(sndbuf,"Client:I receive [%d] data\n", len); ret = lwip_send(s, sndbuf, len, 0); if(ret>0) { printk("socket send %d data\n",ret); } else { ret = lwip_close(s); printk("socket closed %d\n",ret); while(1) sys_msleep(1000); } //sys_msleep(1000); } } void socket_examples_init(void) { //sys_thread_new("socket_nonblocking", socket_nonblocking, NULL, 0, TCPIP_THREAD_PRIO+2); sys_thread_new("socket_timeoutrecv", socket_timeoutrecv, NULL, 0, TCPIP_THREAD_PRIO); } #endif
NightfallDM/xbook2
src/kernel/softirq.c
#include <arch/interrupt.h> #include <xbook/debug.h> #include <xbook/softirq.h> #include <string.h> #include <xbook/bitops.h> /* 普通任务协助队列 */ task_assist_head_t task_assist_head; /* 高级任务协助队列 */ task_assist_head_t high_task_assist_head; /* 软中断表 */ static softirq_action_t softirq_table[NR_SOFTIRQS]; /* 软中断事件的标志 */ static unsigned long softirq_evens; /** * get_softirq_evens - 获取软中断事件 */ static unsigned long get_softirq_evens() { return softirq_evens; } /** * set_softirq_evens - 设置软中断事件 */ static void set_softirq_evens(unsigned long evens) { softirq_evens = evens; } /** * build_softirq - 构建软中断 * @softirq: 软中断号 * @action: 软中断的行为 * * 构建后,软中断才可以激活,才可以找到软中断行为处理 */ void build_softirq(unsigned long softirq, void (*action)(softirq_action_t *)) { /* 在范围内才进行设定 */ if (0 <= softirq && softirq < NR_SOFTIRQS) { /* 把活动添加到软中断表中 */ softirq_table[softirq].action = action; } } /** * active_softirq - 激活软中断 * @softirq: 软中断号 * * 激活后,每当有硬件中断产生,或者主动调用软中断处理的地方时,才会去执行软中断 */ void active_softirq(unsigned long softirq) { /* 在范围内才进行设定 */ if (0 <= softirq && softirq < NR_SOFTIRQS) { /* 在对应位置修改软中断事件 */ if (softirq_table[softirq].action) softirq_evens |= (1 << softirq); } } /** * handle_softirq - 处理软中断 */ static void handle_softirq() { softirq_action_t *action; unsigned long evens; /* 再次处理计数 */ int redoIrq = MAX_REDO_IRQ; /* 获取软中断事件 */ evens = get_softirq_evens(); /*如果在处理软中断过程中又产生了中断,就会导致事件变化,如果 量比较大,就在这里多做几次处理*/ redo: /* 如果有事件,就会逐个运行 */ if (evens) { /* 已经获取了,就置0 */ set_softirq_evens(0); /* 如果有事件,就会逐个运行,由于事件运行可能会花费很多时间, 所以开启中断,允许中断产生 */ action = &softirq_table[0]; /* 打开中断,允许中断产生 */ enable_intr(); /* 处理softirq事件 */ do { /* 如果有软中断事件 */ if (evens & 1) action->action(action); /* 执行软中断事件 */ /* 指向下一个行为描述 */ action++; /* 指向下一个事件 */ evens >>= 1; } while(evens); /* 关闭中断 */ disable_intr(); /* 检查是否还有事件没有处理,也就是说在处理事件过程中,又发生了中断 */ evens = get_softirq_evens(); /* 如果有事件,并且还可以继续尝试处理事件就继续运行 */ if (evens && --redoIrq) goto redo; } /* 已经处理完了,可以返回了 */ } /** * do_softirq - 做软中断处理 * * 通过这个地方,将有机会去处理软中断事件 */ void do_softirq() { unsigned long evens; /* 如果当前硬件中断嵌套,或者有软中断执行,则立即返回。*/ /* 关闭中断 */ unsigned long flags; save_intr(flags); /* 获取事件 */ evens = get_softirq_evens(); /* 有事件就做软中断的处理 */ if (evens) handle_softirq(); /* 恢复之前状态 */ restore_intr(flags); } /** * high_task_assist_schedule - 高级任务协助调度 * @assist: 任务协助 * * 对一个任务协助进行调度,它后面才可以运行 */ void high_task_assist_schedule(task_assist_t *assist) { /* 如果状态还没有调度,才能进行调度 */ if (!test_and_set_bit(HIGHTASK_ASSIST_SOFTIRQ, &assist->status)) { unsigned long flags; save_intr(flags); /* 把任务协助插入到队列最前面 */ assist->next = high_task_assist_head.head; high_task_assist_head.head = assist; /* 激活HIGHTTASKASSIST_SOFTIRQ */ active_softirq(HIGHTASK_ASSIST_SOFTIRQ); restore_intr(flags); } } /** * high_task_assist_action - 高级任务协助行为处理 * @action: 行为 */ static void high_task_assist_action(softirq_action_t *action) { task_assist_t *list; /* 先关闭中断,不然修改链表可能和添加链表产生排斥 */ disable_intr(); /* 获取链表头指针,用于寻找每一个调度的任务协助 */ list = high_task_assist_head.head; /* 把头置空,用于后面添加协助 */ high_task_assist_head.head = NULL; enable_intr(); /* 开始获取并处理协助 */ while (list != NULL) { task_assist_t *assist = list; list = list->next; /* 协助处于打开状态(count == 0, enable) */ if (!atomic_get(&assist->count)) { /* 设置状态为空,不是调度状态 */ clear_bit(TASK_ASSIST_SCHED, &assist->status); /* 执行协助的处理函数 */ assist->func(assist->data); /* 如果协助可以运行,那么运行后就不运行后面重新添加到队列中, 待下次运行 */ continue; } /* 如果写成是关闭状态,那么就重新加入到队列 */ /* 修改链表数据时禁止中断 */ disable_intr(); /* 把任务协助插入到队列最前面 */ assist->next = high_task_assist_head.head; high_task_assist_head.head = assist; /* 激活HIGHTASK_ASSIST_SOFTIRQ */ active_softirq(HIGHTASK_ASSIST_SOFTIRQ); enable_intr(); } } /** * task_assist_schedule - 普通任务协助调度 * @assist: 任务协助 * * 对一个任务协助进行调度,它后面才可以运行 */ void task_assist_schedule(task_assist_t *assist) { /* 如果状态还没有调度,才能进行调度 */ if (!test_and_set_bit(TASK_ASSIST_SOFTIRQ, &assist->status)) { unsigned long flags; save_intr(flags); /* 把任务协助插入到队列最前面 */ assist->next = task_assist_head.head; task_assist_head.head = assist; /* 激活TASK_ASSIST_SOFTIRQ */ active_softirq(TASK_ASSIST_SOFTIRQ); restore_intr(flags); } } /** * task_assist_action - 普通任务协助行为处理 * @action: 行为 */ static void task_assist_action(softirq_action_t *action) { task_assist_t *list; /* 先关闭中断,不然修改链表可能和添加链表产生排斥 */ disable_intr(); /* 获取链表头指针,用于寻找每一个调度的任务协助 */ list = task_assist_head.head; /* 把头置空,用于后面添加协助 */ task_assist_head.head = NULL; enable_intr(); /* 开始获取并处理协助 */ while (list != NULL) { task_assist_t *assist = list; list = list->next; /* 协助处于打开状态(count == 0, enable) */ if (!atomic_get(&assist->count)) { /* 设置状态为空,不是调度状态 */ clear_bit(TASK_ASSIST_SCHED, &assist->status); /* 执行协助的处理函数 */ assist->func(assist->data); /* 如果协助可以运行,那么运行后就不运行后面重新添加到队列中, 待下次运行 */ continue; } /* 如果写成是关闭状态,那么就重新加入到队列 */ /* 修改链表数据时禁止中断 */ disable_intr(); /* 把任务协助插入到队列最前面 */ assist->next = task_assist_head.head; task_assist_head.head = assist; /* 激活TASK_ASSIST_SOFTIRQ */ active_softirq(TASK_ASSIST_SOFTIRQ); enable_intr(); } } /** * init_softirq - 初始化软中断 */ void init_softirq() { /* 初始化软中断事件 */ softirq_evens = 0; /* 设置高级任务协助头为空 */ high_task_assist_head.head = NULL; /* 设置普通任务协助头为空 */ task_assist_head.head = NULL; /* 注册高级任务协助软中断 */ build_softirq(HIGHTASK_ASSIST_SOFTIRQ, high_task_assist_action); /* 注册普通任务协助软中断 */ build_softirq(TASK_ASSIST_SOFTIRQ, task_assist_action); }
NightfallDM/xbook2
src/arch/x86/include/arch/io.h
<gh_stars>0 #ifndef _ARCH_IO_H #define _ARCH_IO_H unsigned char __in8(unsigned int port); unsigned short __in16(unsigned int port); unsigned int __in32(unsigned int port); void __out8(unsigned int port, unsigned int data); void __out16(unsigned int port, unsigned int data); void __out32(unsigned int port, unsigned int data); void __io_read(unsigned short port, void* buf, unsigned int n); void __io_write(unsigned short port, void* buf, unsigned int n); #define in8 __in8 #define in16 __in16 #define in32 __in32 #define out8 __out8 #define out16 __out16 #define out32 __out32 #define io_read __io_read #define io_write __io_write #define io_mfence() __asm__ __volatile__ ("mfence \n\t":::"memory") #endif /* _ARCH_IO_H */
NightfallDM/xbook2
src/include/xbook/bitops.h
#ifndef _XBOOK_BITOPS_H #define _XBOOK_BITOPS_H #include <arch/interrupt.h> /* 求位数值 */ #define low8(a) (unsigned char)((a) & 0xff) #define high8(a) (unsigned char)(((a) >> 8) & 0xff) #define low16(a) (unsigned short)((a) & 0xffff) #define high16(a) (unsigned short)(((a) >> 16) & 0xffff) #define low32(a) (unsigned int)((a) & 0xffffffff) #define high32(a) (unsigned int)(((a) >> 32) & 0xffffffff) /* 合并操作 */ #define merge64(a, b) (unsigned long)((((a) & 0xffffffff) << 32) | ((b) & 0xffffffff)) #define merge32(a, b) (unsigned int)((((a) & 0xffff) << 16) | ((b) & 0xffff)) #define merge16(a, b) (unsigned short)((((a) & 0xff) << 8) | ((b) & 0xff)) #define merge8(a, b) (unsigned char)((((a) & 0xf) << 4) | ((b) & 0xf)) /** * set_bit - 设置位为1 * @nr: 要设置的位置 * @addr: 要设置位的地址 * 将addr的第nr(nr为0-31)位置值置为1, * nr大于31时,把高27的值做为当前地址的偏移,低5位的值为要置为1的位数 */ static inline unsigned long set_bit(int nr, unsigned long *addr) { unsigned long mask, retval; addr += nr >> 5; //nr大于31时,把高27的值做为当前地址的偏移, mask = 1 << (nr & 0x1f); //获取31范围内的值,并把1向左偏移该位数 disable_intr(); //关所有中断 retval = (mask & *addr) != 0; //位置置1 *addr |= mask; enable_intr(); //开所有中断 return retval; //返回置数值 } /** * clear_bit - 把位置0 * @nr: 要设置的位置 * @addr: 要设置位的地址 * * 将addr的第nr(nr为0-31)位置值置为0; * nr大于31时,把高27的值做为当前地址的偏移,低5位的值为要置为0的位数 */ static inline unsigned long clear_bit(int nr, unsigned long *addr) { unsigned long mask, retval; addr += nr >> 5; mask = 1 << (nr & 0x1f); disable_intr(); retval = (mask & *addr) != 0; *addr &= ~mask; enable_intr(); return retval; } /** * test_bit - 测试位的值 * @nr: 要测试的位置 * @addr: 要设置位的地址 * * 判断addr的第nr(nr为0-31)位置的值是否为1; * nr大于31时,把高27的值做为当前地址的偏移,低5位的值为要判断的位数; */ static inline unsigned long test_bit(int nr, unsigned long *addr) { unsigned long mask; addr += nr >> 5; mask = 1 << (nr & 0x1f); return ((mask & *addr) != 0); } /** * test_and_set_bit - 测试并置1 * @nr: 要测试的位置 * @addr: 要设置位的地址 * * 先测试,获取原来的值,再设置为1 */ static inline unsigned long test_and_set_bit(int nr, unsigned long *addr) { unsigned long old; /* 先测试获得之前的值 */ old = test_bit(nr, addr); /* 再值1 */ set_bit(nr, addr); /* 返回之前的值 */ return old; } #endif /* _XBOOK_BITOPS_H */
NightfallDM/xbook2
library/xlibc/include/sys/proc.h
<reponame>NightfallDM/xbook2<filename>library/xlibc/include/sys/proc.h<gh_stars>0 #ifndef _SYS_PROC_H #define _SYS_PROC_H #include "kfile.h" #include <types.h> #define PROC_NAME_LEN 32 /* 任务状态 */ typedef struct _tstate { pid_t ts_pid; /* 进程id */ pid_t ts_ppid; /* 父进程id */ pid_t ts_tgid; /* 线程组id */ char ts_state; /* 运行状态 */ unsigned long ts_priority; /* 优先级 */ unsigned long ts_timeslice; /* 时间片 */ unsigned long ts_runticks; /* 运行的ticks数 */ char ts_name[PROC_NAME_LEN]; /* 任务名字 */ } tstate_t; /* process */ pid_t fork(); void _exit(int status); int wait(int *status); int waitpid(pid_t pid, int *status, int options); int execraw(char *name, char *argv[]); int execfile(char *name, kfile_t *file, char *argv[]); pid_t getpid(); pid_t getppid(); pid_t gettid(); unsigned long sleep(unsigned long second); void sched_yeild(); int tstate(tstate_t *ts, int *idx); int getver(char *buf, int len); #endif /* _SYS_PROC_H */
NightfallDM/xbook2
src/include/xbook/gui.h
<filename>src/include/xbook/gui.h #ifndef _XBOOK_GUI_H #define _XBOOK_GUI_H void init_gui(); #endif /* _XBOOK_GUI_H */
NightfallDM/xbook2
library/xlibc/math/cos.c
/* File: cos.c Contains: For cos(x) Written by: GUI Copyright: (C) 2017-2020 by GuEe Studio for Book OS. All rights reserved. */ #include <math.h> M_FLOAT cos(M_FLOAT x) { return sin(x + MATH_PI_2); }
NightfallDM/xbook2
library/xlibc/include/sys/sys.h
<reponame>NightfallDM/xbook2<filename>library/xlibc/include/sys/sys.h<gh_stars>0 #ifndef _SYS_SYS_H #define _SYS_SYS_H #define SYS_VER_LEN 48 #endif /* _SYS_SYS_H */
NightfallDM/xbook2
user/bosh/main.c
#include <stdio.h> #include <xcons.h> #include <string.h> #include <unistd.h> #include "cmd.h" #include "shell.h" int main(int argc, char *argv[]) { printf("book os shell -v 0.01\n"); if (init_cmd_man() < 0) { printf("init cmd failed!\n"); return -1; } cmd_loop(); exit_cmd_man(); return 0; }
NightfallDM/xbook2
src/gui/lowlevel/mouse.c
#include <string.h> #include <stdio.h> #include <xbook/driver.h> #include <sys/ioctl.h> #include <xbook/kmalloc.h> #include <xbook/vmarea.h> /// 程序本地头文件 #include <gui/mouse.h> #include <gui/screen.h> #include <gui/event.h> #include <sys/input.h> #include <gui/console/console.h> #include <gui/text.h> #include <gui/rect.h> #ifndef GUI_MOUSE_DEVICE_NAME #define GUI_MOUSE_DEVICE_NAME "mouse" #endif gui_mouse_t gui_mouse = {0}; static int mouse_handle = 0; void gui_mouse_show(int x, int y) { /* 转换成格子对齐坐标 */ int cx = x / gui_con_screen.char_width; int cy = y / gui_con_screen.char_height; int last_cx = gui_mouse.last_x / gui_con_screen.char_width; int last_cy = gui_mouse.last_y / gui_con_screen.char_height; /*if (cx == last_cx && cy == last_cy) return;*/ int dx, dy; dx = gui_mouse.last_x / gui_con_screen.char_width * gui_con_screen.char_width; dy = gui_mouse.last_y / gui_con_screen.char_height * gui_con_screen.char_height; /* 绘制原来的位置 */ char ch; con_get_char(&ch, last_cx, last_cy); GUI_COLOR bgcolor; GUI_COLOR fontcolor; /* 根据状态选择背景颜色 */ /* 如果原来的是背景色 */ if (gui_mouse.old_color == gui_screen.gui_to_screen_color(gui_con_screen.background_color)) { bgcolor = gui_con_screen.background_color; fontcolor = gui_con_screen.font_color; } else { /* 是选中颜色 */ bgcolor = (0xffffff - (gui_con_screen.background_color & 0xffffff)) | (0xff << 24); fontcolor = (0xffffff - (gui_con_screen.font_color & 0xffffff)) | (0xff << 24); } /* 绘制背景 */ gui_draw_rect_fill(dx, dy, gui_con_screen.char_width, gui_con_screen.char_height, bgcolor); if (0x20 <= ch && ch <= 0x7e) { /* 绘制字符 */ gui_draw_word(dx, dy, ch, fontcolor); } dx = x / gui_con_screen.char_width * gui_con_screen.char_width; dy = y / gui_con_screen.char_height * gui_con_screen.char_height; /* 读取屏幕上的颜色 */ SCREEN_COLOR scolor; gui_screen.input_pixel(dx, dy, &scolor); /* 纪录旧颜色 */ gui_mouse.old_color = scolor; /* 读取字符 */ con_get_char(&ch, cx, cy); bgcolor = gui_con_screen.mouse_color; /* 绘制背景 */ gui_draw_rect_fill(dx, dy, gui_con_screen.char_width, gui_con_screen.char_height, bgcolor); if (0x20 <= ch && ch <= 0x7e) { /* 绘制字符 */ gui_draw_word(dx, dy, ch, fontcolor); } /* 更新最新值 */ gui_mouse.last_x = x; gui_mouse.last_y = y; } static void gui_mouse_button_down(int btn) { #if DEBUG_LOCAL == 1 printf("[mouse ] %d button down.\n", btn); printf("[mouse ] x:%d, y:%d\n", gui_mouse.x, gui_mouse.y); #endif gui_mouse.show(gui_mouse.x, gui_mouse.y); gui_event e; e.type = GUI_EVENT_MOUSE_BUTTON; e.button.button = btn; e.button.state = GUI_PRESSED; e.button.x = gui_mouse.x; e.button.y = gui_mouse.y; gui_event_add(&e); } static void gui_mouse_button_up(int btn) { #if DEBUG_LOCAL == 1 printf("[mouse ] %d button up.\n", btn); printf("[mouse ] x:%d, y:%d\n", gui_mouse.x, gui_mouse.y); #endif gui_mouse.show(gui_mouse.x, gui_mouse.y); gui_event e; e.type = GUI_EVENT_MOUSE_BUTTON; e.button.button = btn; e.button.state = GUI_RELEASED; e.button.x = gui_mouse.x; e.button.y = gui_mouse.y; gui_event_add(&e); } void gui_mouse_motion() { /* 对鼠标进行修复 */ if (gui_mouse.x < 0) gui_mouse.x = 0; if (gui_mouse.y < 0) gui_mouse.y = 0; /* if (gui_mouse.x >= gui_screen.width) gui_mouse.x = gui_screen.width - 1; if (gui_mouse.y >= gui_screen.height) gui_mouse.y = gui_screen.height - 1; */ if (gui_mouse.x >= gui_con_screen.columns_width) gui_mouse.x = gui_con_screen.columns_width - 1; if (gui_mouse.y >= gui_con_screen.rows_height) gui_mouse.y = gui_con_screen.rows_height - 1; /* 移动鼠标 */ gui_mouse.show(gui_mouse.x, gui_mouse.y); gui_event e; e.type = GUI_EVENT_MOUSE_MOTION; e.button.state = GUI_NOSTATE; e.button.x = gui_mouse.x; e.button.y = gui_mouse.y; gui_event_add(&e); } static int mouse_open(void) { mouse_handle = device_open( GUI_MOUSE_DEVICE_NAME, 0); if ( mouse_handle < 0 ) return -1; return 0; } static int mouse_close(void) { return device_close(mouse_handle); } static int mouse_read(void) { static int x_rel = 0; static int y_rel = 0; static int flag_rel = 0; struct input_event event; int ret = 0; read_mouse_continue: memset( &event, 0, sizeof(event)); ret = device_read( mouse_handle, &event, sizeof(event), 0); if ( ret < 1 ) return -1; switch (event.type) { case EV_REL: if ( (event.code) == REL_X ) { x_rel += event.value; flag_rel = 1; goto read_mouse_continue; } else if ( (event.code) == REL_Y ) { y_rel += event.value; flag_rel = 1; goto read_mouse_continue; } else if ( (event.code) == REL_WHEEL ) { /* 一个滚轮事件 */ return 0; } else { /* 鼠标其它偏移事件 */ return 0; } break; case EV_KEY: if ( (event.code) == BTN_LEFT ) { /* 左键按下事件,需要传递鼠标位置 */ if (event.value > 0) { gui_mouse.button_down(0); } else { gui_mouse.button_up(0); } return 0; } else if ( (event.code) == BTN_MIDDLE ) { /* 中键按下事件,需要传递鼠标位置 */ if (event.value > 0) { gui_mouse.button_down(1); } else { gui_mouse.button_up(1); } return 0; } else if ( (event.code) == BTN_RIGHT ) { /* 右键按下事件,需要传递鼠标位置 */ if (event.value > 0) { gui_mouse.button_down(2); } else { gui_mouse.button_up(2); } return 0; } else { /* 其它键按下事件,需要传递鼠标位置 */ return 0; } break; case EV_MSC: /* 其它事件 */ return 0; case EV_SYN: /* 同步事件,设置鼠标相对位置 */ gui_mouse.x += x_rel; gui_mouse.y += y_rel; /* 相对位置置0 */ x_rel = 0; y_rel = 0; if ( flag_rel == 1 ) { gui_mouse.motion(); flag_rel = 0; return 0; } flag_rel = 0; break; default: break; } return 0; } int gui_init_mouse() { memset(&gui_mouse, 0, sizeof(gui_mouse)); gui_mouse.open = mouse_open; gui_mouse.close = mouse_close; gui_mouse.read = mouse_read; gui_mouse.x = gui_screen.width / 2; gui_mouse.y = gui_screen.height / 2; gui_mouse.last_x = gui_mouse.x; gui_mouse.last_y = gui_mouse.y; gui_mouse.button_down = gui_mouse_button_down; gui_mouse.button_up = gui_mouse_button_up; gui_mouse.motion = gui_mouse_motion; gui_mouse.show = gui_mouse_show; return 0; }
NightfallDM/xbook2
src/arch/x86/mach-i386/arch.c
<filename>src/arch/x86/mach-i386/arch.c #include <arch/segment.h> #include <arch/gate.h> #include <arch/tss.h> #include <arch/pmem.h> #include <arch/debug.h> #include <arch/pic.h> int init_arch() { /* the first thing is to init debug! */ init_kernel_debug(); /* init segment */ init_segment_descriptor(); /* init interrupt */ init_gate_descriptor(); /* init tss, must after segment, tss will use new segment. */ init_tss(); /* init physic memory management */ init_pmem(); init_pic(); return 0; }
NightfallDM/xbook2
src/include/fsal/fstype.h
#ifndef _FILESRV_CORE_FSTYPE_H #define _FILESRV_CORE_FSTYPE_H #include <fsal/fsal.h> int fstype_register(fsal_t *fsal); int fstype_unregister(fsal_t *fsal); fsal_t *fstype_find(char *name); int init_fstype(); #endif /* _FILESRV_CORE_FSTYPE_H */
NightfallDM/xbook2
library/xlibc/math/sin.c
<filename>library/xlibc/math/sin.c<gh_stars>0 /* File: sin.c Contains: For sin(x) Written by: GUI Copyright: (C) 2017-2020 by GuEe Studio for Book OS. All rights reserved. */ #include <math.h> M_FLOAT sin(M_FLOAT x) { if (fabs(x) < EPSILON) return (0.0); x = -1.0 * (fmod(x, M_PI_D) - MATH_PI); const M_FLOAT B = 4 / MATH_PI; const M_FLOAT C = -4 / (MATH_PI * MATH_PI); M_FLOAT y = B * x + C * x * (x > 0 ? x : -x); y = 0.115 * (y * (y > 0 ? y : -y) - y) + y; return (0.885 * y + 0.115 * y * (y > 0 ? y : -y)); }
NightfallDM/xbook2
src/include/xbook/diskman.h
<reponame>NightfallDM/xbook2 #ifndef _XBOOK_DISKMAN_H #define _XBOOK_DISKMAN_H #include <arch/atomic.h> #include <sys/res.h> #include "driver.h" /* 磁盘驱动器 */ typedef struct { list_t list; /* 信息链表 */ int solt; /* 插槽位置 */ int handle; /* 资源句柄 */ devent_t devent; /* 设备项 */ atomic_t ref; /* 引用计数 */ char virname[DEVICE_NAME_LEN]; /* 虚拟磁盘名字 */ } disk_info_t; #define DISK_SOLT_NR 10 typedef struct { int (*open)(int); int (*close)(int); int (*read)(int , off_t , void *, size_t ); int (*write)(int , off_t , void *, size_t ); int (*ioctl)(int , unsigned int , unsigned long ); } disk_drvier_t; extern disk_drvier_t drv_disk; int disk_probe_device(device_type_t type); void disk_info_print(); int init_disk_driver(); int disk_res_find(char *name); disk_info_t *disk_res_find_info(char *name); #endif /* _XBOOK_DISKMAN_H */
NightfallDM/xbook2
src/arch/x86/include/arch/cmos.h
<reponame>NightfallDM/xbook2 #ifndef _X86_CMOS_H #define _X86_CMOS_H /** CMOS操作端口 **/ #define CMOS_INDEX 0x70 #define CMOS_DATA 0x71 /**CMOS中相关信息偏移*/ #define CMOS_CUR_SEC 0x0 //CMOS中当前秒?(BCD) #define CMOS_ALA_SEC 0x1 //CMOS中?警秒?(BCD) #define CMOS_CUR_MIN 0x2 //CMOS中当前分?(BCD) #define CMOS_ALA_MIN 0x3 //CMOS中?警分?(BCD) #define CMOS_CUR_HOUR 0x4 //CMOS中当前小?(BCD) #define CMOS_ALA_HOUR 0x5 //CMOS中?警小?(BCD) #define CMOS_WEEK_DAY 0x6 //CMOS中一周中当前天(BCD) #define CMOS_MON_DAY 0x7 //CMOS中一月中当前日(BCD) #define CMOS_CUR_MON 0x8 //CMOS中当前月?(BCD) #define CMOS_CUR_YEAR 0x9 //CMOS中当前年?(BCD) #define CMOS_DEV_TYPE 0x12 //CMOS中??器格式 #define CMOS_CUR_CEN 0x32 //CMOS中当前世?(BCD) #define BCD_HEX(n) ((n >> 4) * 10) + (n & 0xf) //BCD?十六?制 #define BCD_ASCII_FIRST(n) (((n<<4)>>4)+0x30) //取BCD的个位并以字符?出,来自UdoOS #define BCD_ASCII_S(n) ((n<<4)+0x30) //取BCD的十位并以字符?出,来自UdoOS /* 获得数据的端口 */ unsigned int cmos_get_hour_hex(); unsigned int cmos_get_min_hex(); unsigned char cmos_get_min_hex8(); unsigned int cmos_get_sec_hex(); unsigned int cmos_get_day_of_month(); unsigned int cmos_get_day_of_week(); unsigned int cmos_get_mon_hex(); unsigned int cmos_get_year(); #endif /* _X86_CMOS_H */
NightfallDM/xbook2
src/include/sys/ioctl.h
<filename>src/include/sys/ioctl.h #ifndef _SYS_IOCTL_H #define _SYS_IOCTL_H /* 设备控制码: 0~15位:命令(0-0x7FFF系统保留,0x8000-0xffff用户自定义) 16~31位:设备类型 */ #ifndef DEVCTL_CODE #define DEVCTL_CODE(type, cmd) \ ((unsigned int) ((((type) & 0xffff) << 16) | ((cmd) & 0xffff))) #endif /* 设备标志 */ #define DEV_NOWAIT 0x01 /* 非阻塞方式 */ /* 定义系统的设备控制码 */ /* 控制台 */ #define CONIO_CLEAR DEVCTL_CODE('c', 1) #define CONIO_SCROLL DEVCTL_CODE('c', 2) #define CONIO_SETCOLOR DEVCTL_CODE('c', 3) #define CONIO_GETCOLOR DEVCTL_CODE('c', 4) #define CONIO_SETPOS DEVCTL_CODE('c', 5) #define CONIO_GETPOS DEVCTL_CODE('c', 6) /* disk */ #define DISKIO_GETSIZE DEVCTL_CODE('d', 1) #define DISKIO_CLEAR DEVCTL_CODE('d', 2) /* tty */ #define TTYIO_CLEAR CONIO_CLEAR #define TTYIO_SCROLL CONIO_SCROLL #define TTYIO_SETCOLOR CONIO_SETCOLOR #define TTYIO_GETCOLOR CONIO_GETCOLOR #define TTYIO_SETPOS CONIO_SETPOS #define TTYIO_GETPOS CONIO_GETPOS #define TTYIO_HOLDER DEVCTL_CODE('t', 1) #define TTYIO_VISITOR DEVCTL_CODE('t', 2) #define TTYIO_DETACH DEVCTL_CODE('t', 3) #define TTYIO_COMBINE DEVCTL_CODE('t', 4) /* net */ #define NETIO_GETMAC DEVCTL_CODE('n', 1) #define NETIO_SETMAC DEVCTL_CODE('n', 2) /* video */ typedef struct _video_info { char bits_per_pixel; /* 每个像素的位数 */ short bytes_per_scan_line; /* 单行的字节数 */ short x_resolution, y_resolution; /* 分辨率x,y */ } video_info_t; #define VIDEOIO_GETINFO DEVCTL_CODE('v', 1) /* get video info */ /* even */ #define EVENIO_GETLED DEVCTL_CODE('e', 1) /* get led states */ /* pipe */ #define PIPEIO_SETRW DEVCTL_CODE('p', 1) /* set reader or writer */ #define PIPEIO_SETOPS DEVCTL_CODE('p', 2) /* set operations */ #endif /* _SYS_IOCTL_H */
NightfallDM/xbook2
library/xlibc/include/srv/netsrv.h
<filename>library/xlibc/include/srv/netsrv.h #ifndef _SRV_FILE_SRV_H #define _SRV_FILE_SRV_H /* file server call */ enum filesrv_call_num { NETSRV_SOCKET = 0, NETSRV_BIND, NETSRV_CONNECT, NETSRV_LISTEN, NETSRV_ACCEPT, NETSRV_SEND, NETSRV_RECV, NETSRV_CLOSE, NETSRV_SENDTO, NETSRV_RECVFROM, NETSRV_WRITE, NETSRV_READ, NETSRV_SHUTDOWN, NETSRV_GETSOCKNAME, NETSRV_GETPEERNAME, NETSRV_GETSOCKOPT, NETSRV_SETSOCKOPT, NETSRV_IOCTL, NETSRV_FCNTL, NETSRV_CALL_NR, /* 最大数量 */ }; #endif /* _SRV_FILE_SRV_H */
NightfallDM/xbook2
library/xlibc/math/tanh.c
/* File: tanh.c Contains: For tanh(x) Written by: GUI Copyright: (C) 2017-2020 by GuEe Studio for Book OS. All rights reserved. */ #include <math.h> M_FLOAT tanh(M_FLOAT x) { double pExponent, nExponent; pExponent = exp(x); nExponent = 1.0 / pExponent; return ((pExponent - nExponent) / (pExponent + nExponent)); }
NightfallDM/xbook2
library/xlibc/include/sys/syscall.h
#ifndef _SYS_SYSCALL_H #define _SYS_SYSCALL_H enum syscall_num { SYS_EXIT, SYS_FORK, SYS_EXECR, SYS_EXECF, SYS_WAITPID, SYS_COEXIST, SYS_GETPID, SYS_GETPPID, SYS_TRIGGER, SYS_TRIGGERON, SYS_TRIGGERACT, SYS_TRIGRET, SYS_SLEEP, SYS_THREAD_CREATE, SYS_THREAD_EXIT, SYS_THREAD_JOIN, SYS_THREAD_CANCEL, SYS_THREAD_DETACH, SYS_GETTID, SYS_THREAD_TESTCANCEL, SYS_THREAD_CANCELSTATE, SYS_THREAD_CANCELTYPE, SYS_SCHED_YEILD, SYS_WAITQUE_CREATE, SYS_WAITQUE_DESTROY, SYS_WAITQUE_WAIT, SYS_WAITQUE_WAKE, SYS_PROC_RESERVED = 30, /* 预留30个接口给进程管理 */ SYS_HEAP, SYS_MUNMAP, SYS_VMM_RESERVED = 40, /* 预留10个接口给内存管理 */ SYS_GETRES, SYS_PUTRES, SYS_READRES, SYS_WRITERES, SYS_CTLRES, SYS_DEVSCAN, SYS_MMAP, SYS_RES_RESERVED = 50, /* 预留10个接口给资源管理 */ SYS_ALARM, SYS_KTIME, SYS_GETTICKS, SYS_GETTIMEOFDAY, SYS_CLOCK_GETTIME, SYS_TIME_RESERVED = 60, /* 预留10个接口给时间管理 */ SYS_SRVCALL, SYS_SRVCALL_LISTEN, SYS_SRVCALL_ACK, SYS_SRVCALL_BIND, SYS_SRVCALL_UNBIND, SYS_SRVCALL_FETCH, SYS_UNID, SYS_TSTATE, SYS_GETVER, SYS_MSTATE, SYS_USLEEP, /// 文件系统 SYS_OPEN, SYS_CLOSE, SYS_READ, SYS_WRITE, SYS_LSEEK, SYS_ACCESS, SYS_UNLINK, SYS_FTRUNCATE, SYS_FSYNC, SYS_IOCTL, SYS_FCNTL, SYS_TELL, SYS_MKDIR, SYS_RMDIR, SYS_RENAME, SYS_GETCWD, SYS_CHDIR, SYS_EXECVE, SYS_STAT, SYS_FSTAT, SYS_CHMOD, SYS_FCHMOD, SYS_OPENDIR, SYS_CLOSEDIR, SYS_READDIR, SYS_REWINDDIR, /// sockets 套接字 SYS_SOCKET, SYS_BIND, SYS_CONNECT, SYS_LISTEN, SYS_ACCEPT, SYS_SEND, SYS_RECV, SYS_SENDTO, SYS_RECVFROM, SYS_SHUTDOWN, SYS_GETPEERNAME, SYS_GETSOCKNAME, SYS_GETSOCKOPT, SYS_SETSOCKOPT, SYS_IOCTLSOCKET, SYS_SELECT, SYS_DUP, SYS_DUP2, SYS_PIPE, SYS_SHMGET, SYS_SHMPUT, SYS_SHMMAP, SYS_SHMUNMAP, SYS_SEMGET, SYS_SEMPUT, SYS_SEMDOWN, SYS_SEMUP, SYS_MSGGET, SYS_MSGPUT, SYS_MSGSEND, SYS_MSGRECV, SYS_TRIGPENDING, SYS_TRIGPROCMASK, SYS_XCONGET, SYS_XCONCLEAR, SYS_XCONPUT, SYSCALL_NR, }; extern unsigned long __syscall0(unsigned long num); extern unsigned long __syscall1(unsigned long num, unsigned long arg0); extern unsigned long __syscall2(unsigned long num, unsigned long arg0, unsigned long arg1); extern unsigned long __syscall3(unsigned long num, unsigned long arg0, unsigned long arg1, unsigned long arg2); extern unsigned long __syscall4(unsigned long num, unsigned long arg0, unsigned long arg1, unsigned long arg2, unsigned long arg3); /* 进行宏定义 */ #define syscall0(type, num) \ (type) __syscall0((unsigned long ) num) #define syscall1(type, num, arg0) \ (type) __syscall1((unsigned long ) num, (unsigned long ) arg0) #define syscall2(type, num, arg0, arg1) \ (type) __syscall2((unsigned long ) num, (unsigned long ) arg0,\ (unsigned long ) arg1) #define syscall3(type, num, arg0, arg1, arg2) \ (type) __syscall3((unsigned long ) num, (unsigned long ) arg0,\ (unsigned long ) arg1, (unsigned long ) arg2) #define syscall4(type, num, arg0, arg1, arg2, arg3) \ (type) __syscall4((unsigned long ) num, (unsigned long ) arg0,\ (unsigned long ) arg1, (unsigned long ) arg2, (unsigned long ) arg3) #endif /* _SYS_ */
NightfallDM/xbook2
src/arch/x86/mach-i386/pmem.c
<reponame>NightfallDM/xbook2<filename>src/arch/x86/mach-i386/pmem.c #include <arch/pmem.h> #include <arch/page.h> #include <arch/bootmem.h> #include <xbook/debug.h> #include <math.h> #include <string.h> extern unsigned int get_memory_size_from_hardware(); /* 申请一个内存节点数组,通过引用来表明是否被使用 指向内存节点数组的指针 */ mem_node_t *mem_node_table; /* 节点数量 */ unsigned int mem_node_count; /* 节点基地址 */ unsigned int mem_node_base; /* 物理内存总大小 */ static unsigned long total_pmem_size; mem_node_t *get_free_mem_node() { mem_node_t *node = mem_node_table; while (node < mem_node_table + mem_node_count) { /* 没有被分配就是我们需要的 */ if (!node->reference) { return node; } /* 指向下一个节点位置 */ if (node->count) node += node->count; else node++; } return NULL; } mem_node_t *__page2mem_node(unsigned int page) { int index = (page - mem_node_base) >> PAGE_SHIFT; mem_node_t *node = mem_node_table + index; /* 必须是在正确的范围 */ if (node < mem_node_table || node >= mem_node_table + mem_node_count) return NULL; return node; } unsigned int __mem_node2page(mem_node_t *node) { int index = node - mem_node_table; return mem_node_base + (index << PAGE_SHIFT); } void dump_mem_node(mem_node_t *node) { printk("----Mem Node----\n"); printk("count: %d flags:%x reference:%d\n", node->count, node->flags, node->reference); if (node->cache && node->group) { printk("cache: %x group:%x\n", node->cache, node->group); } } /* * ZoneCutUesdMemory - 把已经使用的内存剪掉 * * 因为内存管理器本身要占用一定内存,在这里把它从可分配中去掉 */ static void cut_used_mem() { /* 剪切掉引导分配的空间 */ unsigned int used_mem = boot_mem_size(); unsigned int used_pages = DIV_ROUND_UP(used_mem, PAGE_SIZE); __alloc_pages(used_pages); } /** * __get_free_page_nr - 获取物理内存空闲页数 * * 返回物理空闲页数 */ unsigned long __get_free_page_nr() { mem_node_t *node = mem_node_table; unsigned long free_nodes = 0; while (node < mem_node_table + mem_node_count) { /* 没有被分配就是我们需要的 */ if (!node->reference) { free_nodes++; } /* 指向下一个节点位置 */ if (node->count) node += node->count; else node++; } /* 获取空闲节点数后,进行计算 */ return free_nodes; } /** * __get_total_page_nr - 获取物理内存总页数 * * 返回物理内存总页数 */ unsigned long __get_total_page_nr() { return total_pmem_size / PAGE_SIZE; } /** * init_pmem - 初始化物理内存管理以及一些相关设定 */ int init_pmem() { //----获取内存大小---- total_pmem_size = get_memory_size_from_hardware(); /* 根据内存大小划分区域 如果内存大于1GB: 1G预留128MB给非连续内存,其余给内核和用户程序平分,内核多余的部分分给用户 如果内存小于1GB: 预留128MB给非连续内存,其余平分给内核和用户程序 */ unsigned int normal_size; unsigned int user_size; normal_size = (total_pmem_size - (NORMAL_MEM_ADDR + HIGH_MEM_SIZE + NULL_MEM_SIZE)) / 2; user_size = total_pmem_size - normal_size; if (normal_size > 1*GB) { unsigned int more_size = normal_size - 1*GB; /* 挪出多余的给用户 */ user_size += more_size; normal_size -= more_size; } /* 由于引导中只映射了0~8MB,所以这里从DMA开始 */ mem_self_mapping(DMA_MEM_ADDR, NORMAL_MEM_ADDR + normal_size); /* 根据物理内存大小对内存分配器进行限定 */ init_boot_mem(PAGE_OFFSET + NORMAL_MEM_ADDR , PAGE_OFFSET + (NORMAL_MEM_ADDR + normal_size)); /* 节点数量就是页数量 */ mem_node_count = (normal_size + user_size)/PAGE_SIZE; mem_node_base = NORMAL_MEM_ADDR; unsigned int mem_node_table_size = mem_node_count * SIZEOF_MEM_NODE; /* 分配内存节点数组 */ mem_node_table = boot_mem_alloc(mem_node_table_size); if (mem_node_table == NULL) { panic("boot mem alloc for mem node table failed!\n"); } //printk(KERN_DEBUG "mem node table at %x size:%x %d MB\n", (unsigned int )mem_node_table, mem_node_table_size, mem_node_table_size/MB); memset(mem_node_table, 0, mem_node_table_size); cut_used_mem(); #if 0 /* test */ unsigned int a = __alloc_pages(1000); unsigned int b = __alloc_pages(2); unsigned int c = __alloc_pages(10); printk("a=%x,b=%x,c=%x\n", a, b, c); __free_pages(c); __free_pages(b); __free_pages(a); a = __alloc_pages(2); b = __alloc_pages(3); c = __alloc_pages(4); printk("a=%x,b=%x,c=%x\n", a, b, c); void *pa = __va((void *)a); void *pb = __pa(b); printk("a=%x,b=%x\n", pa, pb); memset(pa, 1, PAGE_SIZE * 2); __map_pages(0xc63fa000, 10 * PAGE_SIZE, PG_RW_W | PG_US_S); char *v = (char *)0xc63fa000; memset(v, 0xff, 10 * PAGE_SIZE); __unmap_pages(v, 10 * PAGE_SIZE); __map_pages_safe((void *)0xc53fa000, 10 * PAGE_SIZE, PG_RW_W | PG_US_S); v = (char *)0xc53fa000; memset(v, 0xff, 10 * PAGE_SIZE); __unmap_pages_safe(v, 10 * PAGE_SIZE); /* UnmapPages(0xc5000000, PAGE_SIZE * 100); MapPages(0xc6000000, PAGE_SIZE * 200, PAGE_RW_W | PAGE_US_S); v = (char *)0xc6000000; memset(v, 1, PAGE_SIZE * 200); UnmapPages(0xc6000000, PAGE_SIZE * 200); */ //memset(v, 0, PAGE_SIZE * 2); #endif return 0; }
NightfallDM/xbook2
src/arch/x86/mach-i386/debug.c
<reponame>NightfallDM/xbook2<gh_stars>0 #include <arch/debug.h> #include <arch/config.h> /** * init_kernel_debug * */ //define "debug_putchar" void (*debug_putchar)(char ch); void init_kernel_debug() { #if CONFIG_DEBUG_METHOD == 1 // 初始化控制台 init_console_debug(); debug_putchar = &console_putchar; #elif CONFIG_DEBUG_METHOD == 2 // 初始化串口 init_serial_debug(); debug_putchar = &serial_putchar; #endif /* CONFIG_DEBUG_METHOD */ }
NightfallDM/xbook2
src/include/xbook/pipe.h
<reponame>NightfallDM/xbook2<filename>src/include/xbook/pipe.h #ifndef _XBOOK_PIPE_H #define _XBOOK_PIPE_H #include "mutexlock.h" #include "fifobuf.h" #include "waitqueue.h" #include <list.h> #include <stdint.h> #include <types.h> #define PIPE_SIZE 4096 /* pipe flags */ enum { PIPE_NOWAIT = 0x01, }; /* 管道结构 */ typedef struct { list_t list; /* 链表 */ kobjid_t id; /* id号 */ fifo_buf_t *fifo; /* 数据缓冲区 */ uint16_t flags; /* 管道标志 */ uint8_t rdflags; /* 读端标志 */ uint8_t wrflags; /* 写端标志 */ atomic_t read_count; /* 读引用计数 */ atomic_t write_count; /* 写引用计数 */ mutexlock_t mutex; /* 读写互斥 */ wait_queue_t wait_queue; /* 等待队列 */ } pipe_t; pipe_t *create_pipe(); int destroy_pipe(pipe_t *pipe); int pipe_read(kobjid_t pipeid, void *buffer, size_t bytes); int pipe_write(kobjid_t pipeid, void *buffer, size_t bytes); int pipe_close(kobjid_t pipeid, int rw); int pipe_ioctl(kobjid_t pipeid, unsigned int cmd, unsigned long arg, int rw); int pipe_grow(kobjid_t pipeid, int rw); #endif /* _XBOOK_PIPE_H */
NightfallDM/xbook2
src/include/xbook/softirq.h
<reponame>NightfallDM/xbook2 #ifndef _XBOOK_SOFTIRQ_H #define _XBOOK_SOFTIRQ_H #include <arch/atomic.h> #include <types.h> #include <stddef.h> /* 软中断 */ /* 最大的软中断数量 */ #define MAX_NR_SOFTIRQS 32 #define MAX_REDO_IRQ 10 /* 定义软中断类型 */ enum { HIGHTASK_ASSIST_SOFTIRQ = 0, TIMER_SOFTIRQ, NET_TX_SOFTIRQ, NET_RX_SOFTIRQ, TASK_ASSIST_SOFTIRQ, SCHED_SOFTIRQ, RCU_SOFTIRQ, /* Preferable RCU should always be the last softirq */ NR_SOFTIRQS }; /* 软中断行为 */ typedef struct softirq_action { void (*action)(struct softirq_action *); } softirq_action_t; /* 软中断处理函数原型 void softirq_handler(struct softirq_action *action); */ void build_softirq(unsigned long softirq, void (*action)(softirq_action_t *)); void active_softirq(unsigned long softirq); void init_softirq(); /* task_assist, 任务协助 */ #define TASK_ASSIST_SCHED 0 typedef struct task_assist { struct task_assist *next; // 指向下一个任务协助 unsigned long status; // 状态 atomic_t count; // 任务协助的开启与关闭,0(enable),1(disable) void (*func)(unsigned long); // 要执行的函数 unsigned long data; // 回调函数的参数 } task_assist_t; typedef struct task_assist_head { task_assist_t *head; } task_assist_head_t; /* 任务协助处理函数原型 void task_assist_handler(unsigned long); */ void task_assist_schedule(task_assist_t *assist); void high_task_assist_schedule(task_assist_t *assist); /** * task_assist_init - 初始化一个任务协助 * @assist: 任务协助的地址 * @func: 要处理的函数 * @data: 传入的参数 */ static inline void task_assist_init(task_assist_t *assist, void (*func)(unsigned long), unsigned long data) { assist->next = NULL; assist->status = 0; atomic_set(&assist->count, 0); assist->func = func; assist->data = data; } /* 初始化一个任务协助,使能的,enable */ #define DECLEAR_TASK_ASSIST(name, func, data) \ struct task_assist name = {NULL, 0, ATOMIC_INIT(0),func, data} /* 初始化一个任务协助,不使能的,disable */ #define DECLEAR_TASK_ASSIST_DISABLED(name, func, data) \ struct task_assist name = {NULL, 0, ATOMIC_INIT(1),func, data} /** * task_assistDisable - 不让任务协助生效 * @assist: 任务协助 */ static inline void task_assist_disable(task_assist_t *assist) { /* 减小次数,使其disable */ atomic_dec(&assist->count); } /** * task_assistEnable - 让任务协助生效 * @assist: 任务协助 */ static inline void task_assist_enable(task_assist_t *assist) { /* 增加次数,使其enable */ atomic_inc(&assist->count); } #endif /* _XBOOK_SOFTIRQ_H */
NightfallDM/xbook2
library/xlibc/include/arch/x86/xchg.h
#ifndef _LIB_x86_XCHG_H #define _LIB_x86_XCHG_H char __xchg8(char *ptr, char value); short __xchg16(short *ptr, short value); int __xchg32(int *ptr, int value); /** * __Xchg: 交换一个内存地址和一个数值的值 * @x: 数值 * @ptr: 内存指针 * @size: 地址值的字节大小 * * 返回交换前地址中的值 */ static inline unsigned int __xchg(unsigned int x, volatile void * ptr, int size) { int old; switch (size) { case 1: old = __xchg8((char *)ptr, x); break; case 2: old = __xchg16((short *)ptr, x); break; case 4: old = __xchg32((int *)ptr, x); break; } return old; } #define xchg(ptr,v) ((__typeof__(*(ptr)))__xchg((unsigned int) \ (v),(ptr),sizeof(*(ptr)))) /* 定义出口 */ #define __test_and_set(v, new) (xchg((v), new)) #endif /* _LIB_x86_XCHG_H */
NightfallDM/xbook2
src/arch/x86/include/arch/time.h
#ifndef _ARCH_TIME_H #define _ARCH_TIME_H unsigned int cmos_get_hour_hex(); unsigned int cmos_get_min_hex(); unsigned char cmos_get_min_hex8(); unsigned int cmos_get_sec_hex(); unsigned int cmos_get_day_of_month(); unsigned int cmos_get_day_of_week(); unsigned int cmos_get_mon_hex(); unsigned int cmos_get_year(); void __init_pit_clock(); /* clock hardware init */ #define __init_clock_hardware __init_pit_clock /* HZ */ #define __HZ (100 * 5) /* get time */ #define __get_time_hour cmos_get_hour_hex #define __get_time_minute cmos_get_min_hex #define __get_time_second cmos_get_sec_hex #define __get_time_day cmos_get_day_of_month #define __get_time_month cmos_get_mon_hex #define __get_time_year cmos_get_year #define __get_time_week cmos_get_day_of_week void __udelay(int usec); /* clock hardware init */ #define init_clock_hardware __init_pit_clock /* HZ */ #define HZ __HZ /* get time */ #define get_time_hour __get_time_hour #define get_time_minute __get_time_minute #define get_time_second __get_time_second #define get_time_day __get_time_day #define get_time_month __get_time_month #define get_time_year __get_time_year #define get_time_week __get_time_week #define udelay __udelay #endif /* _ARCH_TIME_H */
feixian/ffmpegPackage
Example/ffmpegLib/ZYFViewController.h
// // ZYFViewController.h // ffmpegLib // // Created by hualaiTech on 10/10/2019. // Copyright (c) 2019 hualaiTech. All rights reserved. // @import UIKit; @interface ZYFViewController : UIViewController @end
NULLCT/YBTS
src/ofxNotification.h
#pragma once #include "ofMain.h" class ofxNotification { public: void set(ofTrueTypeFont &_font); void notice(ofColor _back, ofColor _word, string _text); void draw(); ofColor back, word; private: const int animelim = 60 * 2; bool drawtrigger = false; int countframe; int ypos; int alpha; ofTrueTypeFont font; string text; };
NULLCT/YBTS
src/ofApp.h
<filename>src/ofApp.h #pragma once #include "ofMain.h" #include <limits> #include "ofxButton.h" #include "ofxNotification.h" #include "ofxNumSetter.h" #include "ofxPiyo.h" /* TODO: */ class ofApp : public ofBaseApp { public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); /*Made by myself functions*/ void buttonSet(); void showISBNList(ofTrueTypeFont &_font); void showUnixTime(ofTrueTypeFont &_font); void showMousePos(ofTrueTypeFont &_font); void updateISBNShowList(); void removeISBNShowList(); void decisionISBN(); void writeNowUnixTime(); ~ofApp(); private: /*Screen control*/ int screen = 0; // 0=>welcome page, 1=>sold page bool fullscreentr = false; /*Splash Image*/ ofImage splash; int splashtime = 120; /*ISBN Date*/ vector<string> isbnraw; // List of isbn numbers in shop (isbnraw.txt) vector<string> isbnsold; // List of sold book's isbn (isbnsold.txt) vector<string> isbnsoldtime; // List of the time when the book was sold // (isbnsoldtime.txt) int isbncoupon = 0; // Count how many coupon used (isbncoupon.txt) const int bookcost = 100; ofFile isbnsoldstr, isbnsoldtimestr, isbncouponstr; /*ISBN input system*/ string isbninputbuf = ""; // type num will in this vector<string> isbnlist; // isbninputbuf will in this when type return(enter) /*Font*/ ofTrueTypeFont font32jp; // Font for ofxButton ofTrueTypeFont font16; // Font for ofApp::showunixtime() /*Piyo*/ Piyo piyo[15]; bool piyotr = true; /*Me*/ ofImage me; /*Buttons*/ // screen: 0 ofxButton welcome; // "お仕事をはじめる" button ofxButton saveunixtime; // for save unix time ofxButton about; // about me // screen: 1 vector<ofxButton> isbnshowlist; // is 5 best? vector<ofxButton> isbnshowlistatpos; // is 5 best? int isbnshowliststartpos = 0; ofxButton allremove; ofxNumSetter couponnumsetter; ofxButton subtotal; ofxButton coupontotal; ofxButton total; ofxButton decision; ofxNotification notification; };
NULLCT/YBTS
src/ofxPiyo.h
#pragma once #include <time.h> #include <random> #include "ofMain.h" class Piyo { public: Piyo(); void run(); double noisex = 0, noisey = 0; private: ofImage piyoimage; int lim = 200; int x, y, w, h; int replaceframe = 60 * 10; };
sharathbp/WarAndPeace
src/game.h
<reponame>sharathbp/WarAndPeace /* * game.h * * Created on: 01-May-2019 * Author: sharath */ #include <iostream> #include <stdlib.h> #include <list> #include <iterator> #include <string> #include <math.h> #include <GL/glut.h> #include "stb/stb_image.h" #pragma warning(disable:4996) using namespace std; #ifndef GAME_H_ #define GAME_H_ #define BEGIN 1 #define WAR 2 #define PEACE 3 struct coord{ float x; float y; float z; }; ////////////////////////// GLUT FUNCTIONS ///////////////////////// void war(); void reshape(int , int ); void create_menu(); void war_display(); void control(unsigned char , int , int ); void special_control(int , int , int ); void war_mousehandle(int, int , int , int); void menu(int ); ////////////////////////// COLLISSION DETECTION ////////////////// bool collision(struct coord, struct coord); //////////////////////////// TIMER FUNCTIONS ///////////////////// void generate_opponent(int); void opponent_shoot(int ); void terrain_animate(int ); void update(int); void blast(int); void ammo_relode(int); //////////////////////////// SHOOT OPPONENT////////////////////// void generate_bullet(std::list<struct coord>* , struct coord); //////////////////////////// DRAW FUNCTIONS ///////////////////// void draw_bullet(coord); void draw_circle(float , float , float , float ); void draw_rectangle(float, float, float, float); void draw_mountain(); void draw_opponent(coord); void draw_plane(); void draw_terrain(); void draw_text(float , float , float , string ); void draw_text2(float , float , float , string ); void strokeString(float , float , float , float, string ); GLuint LoadTexture(const char*); ////////////////////////////////////////////////////////////////// /////////////////////////// PEACE //////////////////////////////// void peace(); void peace_display(); void plane_landing1(int ); void plane_landing2(int ); void agreement(int ); void draw_man1(); void draw_man2(); void leg_move(int ); #endif /* GAME_H_ */
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_9/projects/01/01.c
<gh_stars>0 #include <stdio.h> void selection_sort(int arr[], int n); int main(void) { int i, arr[10]; printf("Please enter 10 integers: "); for (i = 0; i < 10; i++) scanf("%d", &arr[i]); selection_sort(arr, 10); printf("Sorted list: "); for (i = 0; i < 10; i++) printf("%d ", arr[i]); } void selection_sort(int arr[], int n) { int i, temp, max_index = 0; if (n == 0) return; for (i = 0; i < n; i++) { if (arr[max_index] < arr[i]) max_index = i; } temp = arr[n - 1]; arr[n - 1] = arr[max_index]; arr[max_index] = temp; selection_sort(arr, n - 1); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_7/projects/13/13.c
#include <stdio.h> int main(void) { char in_word, c; float word_count, total_word_length; printf("Enter a sentence: "); in_word = 0; total_word_length = 0; word_count = 0; while ((c = getchar()) != '\n') { if (c == ' ') { if (in_word) in_word = 0; } else { if (in_word) total_word_length++; else { total_word_length++; word_count++; in_word = 1; } } } printf("Average word length: %.1f", total_word_length / word_count); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/10/10.c
#include <stdio.h> int main(void) { int input_hours, input_minutes, input_minutes_since_midnight; int departures[8] = {480, 583, 679, 767, 840, 945, 1140, 1305}; printf("Enter a 24-hour time: "); scanf("%2d:%2d", &input_hours, &input_minutes); input_minutes_since_midnight = input_hours * 60 + input_minutes; printf("Closest departure time is "); if (input_minutes_since_midnight <= departures[0] + (departures[1] - departures[0]) / 2) printf("8:00 a.m., arriving at 10:16 a.m."); else if (input_minutes_since_midnight < departures[1] + (departures[2] - departures[1]) / 2) printf("9:43 a.m., arriving at 11:52 a.m."); else if (input_minutes_since_midnight < departures[2] + (departures[3] - departures[2]) / 2) printf("11:19 a.m., arriving at 1:31 p.m."); else if (input_minutes_since_midnight < departures[3] + (departures[4] - departures[3]) / 2) printf("12:47 p.m., arriving at 3:00 p.m."); else if (input_minutes_since_midnight < departures[4] + (departures[5] - departures[4]) / 2) printf("2:00 p.m., arriving at 4:08 p.m."); else if (input_minutes_since_midnight < departures[5] + (departures[6] - departures[5]) / 2) printf("3:45 p.m., arriving at 5:55 p.m."); else if (input_minutes_since_midnight < departures[6] + (departures[7] - departures[6]) / 2) printf("7:00 p.m., arriving at 9:20 p.m."); else printf("9:45 p.m., arriving at 11:58 p.m."); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/09/9.c
#include <stdio.h> #include <ctype.h> int compute_vowel_count(const char *sentence); int main(void) { char sentence[81]; char c, *p = sentence; printf("Enter a sentence: "); while ((c = getchar()) != '\n' && p < sentence + 80) *p++ = c; p = '\0'; printf("Your sentence contains %d vowels.\n", compute_vowel_count(sentence)); return 0; } int compute_vowel_count(const char *sentence) { int vowels = 0; while (*sentence) { switch(toupper(*sentence)) { case 'A': case 'E': case 'I': case 'O': case 'U': vowels++; break; default: break; } sentence++; } return vowels; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_5/projects/11/11.c
<filename>chapter_5/projects/11/11.c<gh_stars>0 #include <stdio.h> int main(void) { int tens_digit, ones_digit; printf("Enter a two-digit number: "); scanf("%1d%1d", &tens_digit, &ones_digit); if (tens_digit == 1) switch (ones_digit) { case 0: printf("Ten"); break; case 1: printf("Eleven"); break; case 2: printf("Twelve"); break; case 3: printf("Thirteen"); break; case 4: printf("Fourteen"); break; case 5: printf("Fifteen"); break; case 6: printf("Sixteen"); break; case 7: printf("Seventeen"); break; case 8: printf("Eighteen"); break; case 9: printf("Nineteen"); break; } else { switch (tens_digit) { case 2: printf("Twenty"); break; case 3: printf("Thirty"); break; case 4: printf("Fourty"); break; case 5: printf("Fifty"); break; case 6: printf("Sixty"); break; case 7: printf("Seventy"); break; case 8: printf("Eighty"); break; case 9: printf("Ninety"); break; } switch (ones_digit) { case 1: printf("-one"); break; case 2: printf("-two"); break; case 3: printf("-three"); break; case 4: printf("-four"); break; case 5: printf("-five"); break; case 6: printf("-six"); break; case 7: printf("-seven"); break; case 8: printf("-eight"); break; case 9: printf("-nine"); break; } } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/15/15.c
#include <stdio.h> int main(void) { char c, shifted_char; int shift_amount = 0; char message[80] = {0}; printf("Enter a message to be encrypted: "); for (int i = 0; (c = getchar()) != '\n'; i++) message[i] = c; printf("Enter shift amount (1-25): "); scanf("%d", &shift_amount); printf("Encrypted message: "); for (int i = 0; message[i] != '\0'; i++) { if (message[i] >= 'A' && message[i] <= 'Z') shifted_char = ((message[i] - 'A') + shift_amount) % 26 + 'A'; else if (message[i] >= 'a' && message[i] <= 'z') shifted_char = ((message[i] - 'a') + shift_amount) % 26 + 'a'; else shifted_char = message[i]; putchar(shifted_char); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_7/projects/10/10.c
#include <stdio.h> #include <ctype.h> int main(void) { char c; int vowel_count = 0; printf("Enter a sentence: "); while ((c = getchar()) != '\n') { switch (tolower(c)) { case 'a': case 'e': case 'i': case 'o': case 'u': vowel_count++; break; } } printf("Your sentence contains %d vowels.", vowel_count); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_12/projects/04/4.c
<filename>chapter_12/projects/04/4.c #include <stdio.h> #include <ctype.h> #define MAX_LENGTH 100 int main(void) { char *p, *q, *r, message[MAX_LENGTH] = {0}; p = message; printf("Enter a message: "); for (char c; (c = getchar()) != '\n' && p < message + MAX_LENGTH;) if (isalpha(c)) *p++ = tolower(c); q = message; r = --p; for (; q <= r; q++, r--) if (*q != *r) { printf("Not a palindrome."); return 0; } printf("Palindrome"); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/03/03.c
<gh_stars>0 /* Checks numbers for repeated digits */ #include <stdio.h> int main(void) { int digit, i, occurrences[10] = {0}; long n; printf("Enter a number: "); scanf("%ld", &n); if (n <= 0) { printf("Digit:\t\t 0 1 2 3 4 5 6 7 8 9\n"); printf("Occurrences:\t 0 0 0 0 0 0 0 0 0 0\n"); } while (n > 0) { while (n > 0) { digit = n % 10; occurrences[digit]++; n /= 10; } printf("Digit:\t\t 0 1 2 3 4 5 6 7 8 9\n"); printf("Occurrences:\t"); for (i = 0; i < 10; i++) { printf("%2d ", occurrences[i]); occurrences[i] = 0; } printf("\nEnter a number: "); scanf("%ld", &n); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/12/12.c
#include <stdio.h> #define MAX_WORDS 30 #define MAX_LEN 20 int main(void) { int i = 0, j = 0; char c; char terminating_char = 0; char sentence[MAX_WORDS][MAX_LEN + 1]; printf("Enter a sentence: "); while ((c = getchar()) != '\n' && i < MAX_WORDS) { if (c == ' ' || c == '\t') { sentence[i][j] = '\0'; i++; j = 0; continue; } if (c == '.' || c == '!' || c == '?') { terminating_char = c; sentence[i][j] = '\0'; break; } else if (j < MAX_LEN) sentence[i][j++] = c; } printf("Reversal of sentence: "); while (i > 0) printf("%s ", sentence[i--]); printf("%s%c\n", sentence[i], terminating_char); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_3/projects/01/01.c
<filename>chapter_3/projects/01/01.c #include <stdio.h> int main(void) { int day, month, year; printf("Enter a date (mm/dd/yyy): "); scanf("%d /%d /%d", &month, &day, &year); printf("You entered the date %.4d%.2d%.2d", year, month, day); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_5/projects/07/07.c
<filename>chapter_5/projects/07/07.c #include <stdio.h> int main(void) { int num_1, num_2, num_3, num_4, max, min; printf("Please enter 4 integers: "); scanf("%d %d %d %d", &num_1, &num_2, &num_3, &num_4); if (num_1 <= num_2 && num_1 <= num_3 && num_1 <= num_4) min = num_1; else if (num_2 <= num_1 && num_2 <= num_3 && num_2 <= num_4) min = num_2; else if (num_3 <= num_1 && num_3 <= num_2 && num_3 <= num_4) min = num_3; else if (num_4 <= num_1 && num_4 <= num_3 && num_4 <= num_2) min = num_4; if (num_1 >= num_2 && num_1 >= num_3 && num_1 >= num_4) max = num_1; else if (num_2 >= num_1 && num_2 >= num_3 && num_2 >= num_4) max = num_2; else if (num_3 >= num_1 && num_3 >= num_2 && num_3 >= num_4) max = num_3; else if (num_4 >= num_1 && num_4 >= num_3 && num_4 >= num_2) max = num_4; printf("Min: %d\n", min); printf("Max: %d\n", max); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/09/09.c
<filename>chapter_6/projects/09/09.c #include <stdio.h> int main(void) { float loan_amount, interest_rate, monthly_payment, monthly_interest_rate; int i, payments; printf("Enter amount of loan: "); scanf("%f", &loan_amount); printf("Enter interest rate: "); scanf("%f", &interest_rate); printf("Enter monthly payment: "); scanf("%f", &monthly_payment); printf("Enter number of payments you want to see: "); scanf("%d", &payments); for (i = 1; i <= payments; i++) { loan_amount = loan_amount - monthly_payment + (loan_amount * interest_rate / 100.0 / 12.0); printf("Balance remaining after payment %d: $%.2f\n", i, loan_amount); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_12/projects/03/3.c
#include <stdio.h> #define MAX_LENGTH 100 int main(void) { char *p, message[MAX_LENGTH] = {0}; p = message; printf("Enter a message: "); for (char c; (c = getchar()) != '\n' && message < &message[MAX_LENGTH - 1]; p++) *p = c; printf("Reversal is: "); for (; p >= message; p--) putchar(*p); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_2/exercises/04/04.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions<gh_stars>0 #include <stdio.h> int main(void) { int foo, bar, baz; float a, b, c; printf("Integers - foo: %d, bar: %d, baz: %d\n", foo, bar, baz); printf("Floats - a: %f, b: %f, c: %f\n", a, b, c); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/08/08.c
#include <stdio.h> #define STUDENTS 5 #define QUIZ_GRADES 5 int main(void) { int matrix[STUDENTS][QUIZ_GRADES], i, j, highest, lowest, total; for (i = 0; i < STUDENTS; i++) { printf("Enter quiz grades for student %d: ", i + 1); for (j = 0; j < QUIZ_GRADES; j++) scanf("%d", &matrix[i][j]); } printf("\nScores per student:\n"); for (i = 0; i < STUDENTS; i++) { printf("Student %d - ", i + 1); for (total = 0, j = 0; j < QUIZ_GRADES; j++) { total += matrix[i][j]; } printf("Total: %d | Average: %.2f\n", total, (float)total / 5.00f); } printf("\nScores per quiz:\n"); for (i = 0; i < QUIZ_GRADES; i++) { printf("Quiz %d - ", i + 1); for (highest = matrix[i][0], lowest = matrix[i][0], total = 0, j = 0; j < STUDENTS; j++) { if (matrix[j][i] > highest) highest = matrix[j][i]; if (matrix[j][i] < lowest) lowest = matrix[j][i]; total += matrix[j][i]; } printf("Highest score: %2d | Lowest score: %2d | Average: %.2f\n", highest, lowest, (float)total / 5.00f); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_7/projects/08/08.c
<gh_stars>0 #include <stdio.h> #include <ctype.h> int main(void) { int input_hours, input_minutes, input_minutes_since_midnight; char time_indicator; int departure_1 = 480; int departure_2 = 583; int departure_3 = 679; int departure_4 = 767; int departure_5 = 840; int departure_6 = 945; int departure_7 = 1140; int departure_8 = 1305; printf("Enter a 12-hour time: "); scanf("%2d:%2d %c", &input_hours, &input_minutes, &time_indicator); if (tolower(time_indicator) == 'a') input_minutes_since_midnight = input_hours * 60 + input_minutes; else input_minutes_since_midnight = (input_hours + 12) * 60 + input_minutes; printf("Closest departure time is "); if (input_minutes_since_midnight <= departure_1 + (departure_2 - departure_1) / 2) printf("8:00 a.m., arriving at 10:16 a.m."); else if (input_minutes_since_midnight < departure_2 + (departure_3 - departure_2) / 2) printf("9:43 a.m., arriving at 11:52 a.m."); else if (input_minutes_since_midnight < departure_3 + (departure_4 - departure_3) / 2) printf("11:19 a.m., arriving at 1:31 p.m."); else if (input_minutes_since_midnight < departure_4 + (departure_5 - departure_4) / 2) printf("12:47 p.m., arriving at 3:00 p.m."); else if (input_minutes_since_midnight < departure_5 + (departure_6 - departure_5) / 2) printf("2:00 p.m., arriving at 4:08 p.m."); else if (input_minutes_since_midnight < departure_6 + (departure_7 - departure_6) / 2) printf("3:45 p.m., arriving at 5:55 p.m."); else if (input_minutes_since_midnight < departure_7 + (departure_8 - departure_7) / 2) printf("7:00 p.m., arriving at 9:20 p.m."); else printf("9:45 p.m., arriving at 11:58 p.m."); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/14/14.c
<filename>chapter_8/projects/14/14.c #include <stdio.h> #define SENTENCE_LENGTH 50 int main(void) { int i, j, k; char c; char debug; char sentence[SENTENCE_LENGTH] = {0}; char terminal; printf("Enter a sentence: "); for (int i = 0; (c = getchar()) != '\n'; i++) { if (c == '.' || c == '?' || c == '!') { terminal = c; break; } else sentence[i] = c; } printf("Reversal of sentence: "); for (i = (SENTENCE_LENGTH - 1); i >= 0; i--) { if (sentence[i - 1] == ' ' || i == 0) { for (k = i; sentence[k] != ' ' && sentence[k] != '\0'; k++) putchar(sentence[k]); if (i != 0) putchar(' '); } } putchar(terminal); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_11/projects/02/02.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> #define DEPARTURE 0 #define ARRIVAL 1 void find_closest_flight(int desired_time, int *departure_time, int *arrival_time); int main(void) { int input_hours, input_minutes, departure_hour, arrival_hour, desired_time, departure_time, arrival_time; printf("Enter a 24-hour time: "); scanf("%2d:%2d", &input_hours, &input_minutes); desired_time = input_hours * 60 + input_minutes; find_closest_flight(desired_time, &departure_time, &arrival_time); departure_hour = departure_time / 60; departure_hour -= departure_hour > 12 ? 12 : 0; arrival_hour = arrival_time / 60; arrival_hour -= arrival_hour > 12 ? 12 : 0; printf("Closest departure time is "); printf("%d:%.2d", departure_hour, departure_time % 60); if (departure_time / 60 >= 12) printf(" p.m."); else printf(" a.m."); printf(", arriving at "); printf("%d:%.2d", arrival_hour, arrival_time % 60); if (arrival_time / 60 >= 12) printf(" p.m."); else printf(" a.m."); return 0; } void find_closest_flight(int desired_time, int *departure_time, int *arrival_time) { int flights[8][2] = {{480, 616}, {583, 712}, {679, 811}, {767, 900}, {840, 968}, {945, 1075}, {1140, 1280}, {1305, 1438}}; if (desired_time <= flights[0][DEPARTURE] + (flights[1][DEPARTURE] - flights[0][DEPARTURE]) / 2) { *departure_time = flights[0][DEPARTURE]; *arrival_time = flights[0][ARRIVAL]; } else if (desired_time < flights[1][DEPARTURE] + (flights[2][DEPARTURE] - flights[1][DEPARTURE]) / 2) { *departure_time = flights[1][DEPARTURE]; *arrival_time = flights[1][ARRIVAL]; } else if (desired_time < flights[2][DEPARTURE] + (flights[3][DEPARTURE] - flights[2][DEPARTURE]) / 2) { *departure_time = flights[2][DEPARTURE]; *arrival_time = flights[2][ARRIVAL]; } else if (desired_time < flights[3][DEPARTURE] + (flights[4][DEPARTURE] - flights[3][DEPARTURE]) / 2) { *departure_time = flights[3][DEPARTURE]; *arrival_time = flights[3][ARRIVAL]; } else if (desired_time < flights[4][DEPARTURE] + (flights[5][DEPARTURE] - flights[4][DEPARTURE]) / 2) { *departure_time = flights[4][DEPARTURE]; *arrival_time = flights[4][ARRIVAL]; } else if (desired_time < flights[5][DEPARTURE] + (flights[6][DEPARTURE] - flights[5][DEPARTURE]) / 2) { *departure_time = flights[5][DEPARTURE]; *arrival_time = flights[5][ARRIVAL]; } else if (desired_time < flights[6][DEPARTURE] + (flights[7][DEPARTURE] - flights[6][DEPARTURE]) / 2) { *departure_time = flights[6][DEPARTURE]; *arrival_time = flights[6][ARRIVAL]; } else { *departure_time = flights[7][DEPARTURE]; *arrival_time = flights[7][ARRIVAL]; } }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/02/02.c
#include <stdio.h> int main(void) { int number_1, temp, number_2, gcd; printf("Enter two integers: "); scanf("%d %d", &number_1, &number_2); for (;;) { if (number_1 == 0) { gcd = number_2; break; } if (number_2 == 0) { gcd = number_1; break; } temp = number_2; number_2 = number_1 % number_2; number_1 = temp; } printf("Greatest common divisor: %d", gcd); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/02/02.c
<filename>chapter_8/projects/02/02.c<gh_stars>0 /* Checks numbers for repeated digits */ #include <stdbool.h> /* C99 only */ #include <stdio.h> int main(void) { int digits[10] = {0}; int i, digit; long n; printf("Enter a number: "); scanf("%ld", &n); while (n > 0) { digit = n % 10; digits[digit]++; n /= 10; } printf("Digit: %6c", ' '); for (i = 0; i < 10; i++) printf("%3d", i); printf("\nOccurrences: "); for (i = 0; i < 10; i++) printf("%3d", digits[i]); printf("\n"); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/02/2.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> #include <string.h> #define MAX_REMIND 50 #define MSG_LEN 60 int read_line(char str[], int n); int main(void) { char reminders[MAX_REMIND][MSG_LEN + 3]; char day_str[22], msg_str[MSG_LEN + 1]; int month, day, hour, minute, i, j, num_remind = 0; for (;;) { if (num_remind == MAX_REMIND) { printf("-- No space left --\n"); break; } printf("Enter reminder: \'mm/dd hh:mm message\': "); scanf(" %2d/ %2d", &month, &day); if (day == 0 || month == 0) break; else if (day < 0 || day > 31) { printf("-- Day out of range 0-31; try again --\n"); while (getchar() != '\n') ; /* discard characters for next scan */ continue; } scanf(" %d: %d", &hour, &minute); sprintf(day_str, "%4.2d%4.2d %2.2d:%.2d ", month, day, hour, minute); read_line(msg_str, MSG_LEN); for (i = 0; i < num_remind; i++) if (strcmp(day_str, reminders[i]) < 0) break; for (j = num_remind; j > i; j--) strcpy(reminders[j], reminders[j-1]); strcpy(reminders[i], day_str); strcat(reminders[i], msg_str); num_remind++; } printf("\nMonth Day Time Reminder\n"); for (i = 0; i < num_remind; i++) printf(" %s\n", reminders[i]); return 0; } int read_line(char str[], int n) { int ch, i = 0; while ((ch = getchar()) != '\n') if (i < n) str[i++] = ch; str[i] = '\0'; return i; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/06/06.c
#include <stdio.h> int main(void) { int max, squarable; printf("Please enter a number: "); scanf("%d", &max); for (squarable = 2; (squarable * squarable) <= max; squarable += 2) printf("%d\n", (squarable * squarable)); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/12/12.c
<gh_stars>0 #include <stdio.h> #include <ctype.h> int main(void) { char c; int values[26] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10}; int value = 0; int index = 0; printf("Enter a word: "); while ((c = getchar()) != '\n') { index = toupper(c) - 'A'; value += values[index]; } printf("Scrabble value: %d\n", value); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/01/1.c
<filename>chapter_13/projects/01/1.c<gh_stars>0 #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdbool.h> #define MAX_WORD_LENGTH 20 int main(void) { char smallest_word[MAX_WORD_LENGTH], largest_word[MAX_WORD_LENGTH], word[MAX_WORD_LENGTH]; int comparison; printf("Enter a word: "); scanf("%20s", word); strcpy(smallest_word, word); strcpy(largest_word, word); for (;;) { printf("Enter a word: "); scanf("%20s", word); if (strcmp(smallest_word, word) > 0) strcpy(smallest_word, word); if (strcmp(largest_word, word) < 0) strcpy(largest_word, word); if (strlen(word) == 4) break; } printf("Smallest word: %s\n", smallest_word); printf("Largest word: %s", largest_word); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_4/projects/04/04.c
#include <stdio.h> int main(void) { int number, octal_digit_1, octal_digit_2, octal_digit_3, octal_digit_4, octal_digit_5; printf("Enter a number between 0 and 32767:"); scanf("%d", &number); octal_digit_5 = number % 8; number /= 8; octal_digit_4 = number % 8; number /= 8; octal_digit_3 = number % 8; number /= 8; octal_digit_2 = number % 8; number /= 8; octal_digit_1 = number % 8; printf("In octal, your number is: %d%d%d%d%d", octal_digit_1, octal_digit_2, octal_digit_3, octal_digit_4, octal_digit_5); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_5/projects/06/06.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions /* Computes a Universal Product Code check digit */ #include <stdio.h> int main(void) { int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, first_sum, second_sum, total, check_digit; printf("Enter UPC digits: "); scanf("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9, &n10, &n11); first_sum = n1 + n3 + n5 + n7 + n9 + n11; second_sum = n2 + n4 + n6 + n8 + n10; total = (3 * first_sum) + second_sum; check_digit = 9 - ((total - 1) % 10); if (check_digit == n12) printf("VALID"); else printf("INVALID"); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_9/projects/06/06.c
<gh_stars>0 #include <stdio.h> int power(int x, int n); int compute_polynomial(int x); int main(void) { int x; printf("Please provide a value for x: "); scanf("%d", &x); return compute_polynomial(x); } int power(int x, int n) { return n == 1 ? x : (x * power(x, n - 1)); } int compute_polynomial(int x) { return (3 * power(x, 5)) + (2 * power(x, 4)) - (5 * power(x, 3)) - power(x, 2) + (7 * x) - 6; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/11/11.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> int main(void) { int n, i, j, factorial_i; float e; printf("Please enter a number: "); scanf("%d", &n); for (e = 1.00f, i = 1; i <= n; ++i) { for (factorial_i = 1, j = 1; j <= i; ++j) { factorial_i *= j; } e += (1.00f / factorial_i); } printf("e: %f", e); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/10/10.c
<gh_stars>0 #include <stdio.h> int main(void) { int day, month, year, min_day, min_month, min_year; printf("Enter a date (mm/dd/yyyy): "); scanf("%d/%d/%d", &min_month, &min_day, &min_year); for (;;) { printf("Enter a date (mm/dd/yyyy): "); scanf("%d/%d/%d", &month, &day, &year); if (day == 0 && month == 0 && year == 0) break; if ((min_year > year) || (min_year == year && min_month > month) || (min_year == year && min_month == month && min_day > day)) min_year = year, min_month = month, min_day = day; } printf("%.2d/%.2d/%.2d is the earliest date.", min_month, min_day, min_year); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_7/projects/11/11.c
#include <stdio.h> int main(void) { char initial, c; printf("Enter a first and last name: "); while ((c = getchar()) == ' ') ; initial = c; while ((c = getchar()) != ' ') ; while ((c = getchar()) == ' ') ; do putchar(c); while ((c = getchar()) != ' ' && c != '\n'); printf(", %c.\n", initial); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_9/projects/07/07.c
#include <stdio.h> int power(int x, int n); int main(void) { int x, n; printf("Please enter x: "); scanf("%d", &x); printf("Please enter n: "); scanf("%d", &n); printf("Result: %d", power(x, n)); return 0; } int power(int x, int n) { if (n == 0) return 1; else if (n % 2 == 0) return power(x, n / 2) * power(x, n / 2); else return x * power(x, n - 1); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_10/projects/06/06.c
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define STACK_SIZE 100 int contents[STACK_SIZE]; int top = 0; void make_empty(void); bool is_empty(void); bool is_full(void); void push(int i); int pop(void); void stack_overflow(void); void stack_underflow(void); int main(void) { char c; printf("Enter an RPN expression: "); while ((c = getchar()) != '\n') { switch (c) { case '0': { push(0); break; } case '1': { push(1); break; } case '2': { push(2); break; } case '3': { push(3); break; } case '4': { push(4); break; } case '5': { push(5); break; } case '6': { push(6); break; } case '7': { push(7); break; } case '8': { push(8); break; } case '9': { push(9); break; } case '+': { int operand_1 = pop(); int operand_2 = pop(); push(operand_1 + operand_2); break; } case '-': { int operand_1 = pop(); int operand_2 = pop(); push(operand_2 - operand_1); break; } case '*': { int operand_1 = pop(); int operand_2 = pop(); push(operand_1 * operand_2); break; } case '/': { int operand_1 = pop(); int operand_2 = pop(); push(operand_2 / operand_1); break; } } } printf("Value of expression: %d", pop()); return 0; } void make_empty(void) { top = 0; } bool is_empty(void) { return top == 0; } bool is_full(void) { return top == STACK_SIZE; } void push(int i) { if (is_full()) stack_overflow(); else contents[top++] = i; } int pop(void) { if (is_empty()) stack_underflow(); else return contents[--top]; } void stack_overflow(void) { printf("\nStack overflow\n"); exit(EXIT_FAILURE); } void stack_underflow(void) { printf("\nStack underflow\n"); exit(EXIT_FAILURE); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_4/projects/01/01.c
#include <stdio.h> int main(void) { int number, digit_1, digit_2; printf("Enter a two-digit number:"); scanf("%d", &number); digit_1 = number / 10; digit_2 = number % 10; printf("The reversal is: %d%d", digit_2, digit_1); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/06/06.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> #include <ctype.h> #define MAX_MESSAGE_LENGTH 120 int main(void) { char c, original_message[MAX_MESSAGE_LENGTH] = {0}; int i = 0; printf("Enter message: "); while ((c = getchar()) != '\n' && i < MAX_MESSAGE_LENGTH) original_message[i++] = c; printf("In B1FF-speak: "); for (i = 0; i < (int)(sizeof(original_message) / sizeof(original_message[0])); i++) { switch (original_message[i]) { case 'a': putchar('4'); break; case 'b': putchar('8'); break; case 'e': putchar('3'); break; case 'i': putchar('1'); break; case 'o': putchar('0'); break; case 's': putchar('5'); break; default: putchar(toupper(original_message[i])); break; } } printf("!!!!!!!!!!\n"); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_5/projects/10/10.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> int main(void) { int grade; printf("Enter numberical grade: "); scanf("%d", &grade); if (grade > 100 || grade < 0) printf("Invalid grade given."); else { printf("Letter grade: "); switch (grade / 10) { case 10: case 9: printf("A"); break; case 8: printf("B"); break; case 7: printf("C"); break; case 6: printf("D"); break; case 5: case 4: case 3: case 2: case 1: case 0: printf("F"); break; } } }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_2/projects/05/05.c
#include <stdio.h> int main(void) { int x, result; printf("Enter a value for x: "); scanf("%d", &x); result = (3 * (x * x * x * x * x)) + (2 * (x * x * x * x)) - (5 * (x * x * x)) - (x * x) + (7 * x) - 6; printf("The result is %d", result); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_2/projects/07/07.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions<gh_stars>0 #include <stdio.h> int main(void) { int dollar_amount, bills_of_twenty, bills_of_ten, bills_of_five, bills_of_one; printf("Enter a dollar amount: "); scanf("%d", &dollar_amount); bills_of_twenty = dollar_amount / 20; dollar_amount -= (bills_of_twenty * 20); bills_of_ten = dollar_amount / 10; dollar_amount -= (bills_of_ten * 10); bills_of_five = dollar_amount / 5; dollar_amount -= (bills_of_five * 5); bills_of_one = dollar_amount / 1; printf("$20 bills: %d\n", bills_of_twenty); printf("$10 bills: %d\n", bills_of_ten); printf("$5 bills: %d\n", bills_of_five); printf("$1 bills: %d\n", bills_of_one); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/10/10.c
<filename>chapter_13/projects/10/10.c #include <stdio.h> void reverse_name(char *name); int main(void) { char name[81]; printf("Enter a first and last name: "); fgets(name, sizeof(name), stdin); reverse_name(name); return 0; } void reverse_name(char *name) { char *p = name, initial; while (*p == ' ') p++; initial = *p++; while (*p && *p++ != ' ') ; while (*p && *p != '\n') putchar(*p++); printf(", %c.\n", initial); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/13/13.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> #define MAX_VALUE 80 void encrypt(char *message, int shift); int main(void) { char c, sentence[MAX_VALUE] = {0}; int i, n; printf("Enter message to be encrypted: "); for (i = 0; (c = getchar()) != '\n' && i < MAX_VALUE; i++) sentence[i] = c; printf("Enter shift amount (1-25): "); scanf("%d", &n); encrypt(sentence, n); printf("%s\n", sentence); return 0; } void encrypt(char *message, int shift) { while (*message) { if (*message >= 'A' && *message <= 'Z') *message = ((*message - 'A') + shift) % 26 + 'A'; else if (*message >= 'a' && *message <= 'z') *message = ((*message - 'a') + shift) % 26 + 'a'; message++; } }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_3/projects/03/03.c
<filename>chapter_3/projects/03/03.c #include <stdio.h> int main(void) { int gs1_prefix, group_identifier, publisher_code, item_number, check_digit; printf("Enter ISBN: "); scanf("%d -%d -%d -%d -%d", &gs1_prefix, &group_identifier, &publisher_code, &item_number, &check_digit); printf("GS1 prefix: %d\n", gs1_prefix); printf("Group identifier: %d\n", group_identifier); printf("Publisher code: %d\n", publisher_code); printf("Item number: %d\n", item_number); printf("Check digit: %d\n", check_digit); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/11/11.c
#include <stdio.h> #include <ctype.h> double compute_average_word_length(const char *sentence); int main(void) { char sentence[101]; printf("Enter a sentence: "); fgets(sentence, sizeof(sentence), stdin); printf("Average word length: %.1f\n", compute_average_word_length(sentence)); return 0; } double compute_average_word_length(const char *sentence) { int words = 0, length = 0; while (*sentence) { while (*sentence && !isspace(*sentence)) { sentence++; length++; } words++; while (*sentence && isspace(*sentence)) sentence++; } return (double) length / words; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_7/projects/06/06.c
#include <stdio.h> int main(void) { printf("Size of short: %lu\n", sizeof(short)); printf("Size of int: %lu\n", sizeof(int)); printf("Size of long: %lu\n", sizeof(long)); printf("Size of float: %lu\n", sizeof(float)); printf("Size of double: %lu\n", sizeof(double)); printf("Size of long double: %lu\n", sizeof(long double)); }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_2/projects/08/08.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> int main(void) { float loan_amount, interest_rate, monthly_payment, monthly_interest_rate; printf("Enter amount of loan: "); scanf("%f", &loan_amount); printf("Enter interest rate: "); scanf("%f", &interest_rate); printf("Enter monthly payment: "); scanf("%f", &monthly_payment); loan_amount = loan_amount - monthly_payment + (loan_amount * interest_rate / 100.0 / 12.0); printf("Balance remaining after first payment: $%.2f\n", loan_amount); loan_amount = loan_amount - monthly_payment + (loan_amount * interest_rate / 100.0 / 12.0); printf("Balance remaining after second payment: $%.2f\n", loan_amount); loan_amount = loan_amount - monthly_payment + (loan_amount * interest_rate / 100.0 / 12.0); printf("Balance remaining after third payment: $%.2f\n", loan_amount); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_10/projects/07/07.c
<filename>chapter_10/projects/07/07.c #include <ctype.h> #include <stdio.h> #include <stdlib.h> #define MAX_DIGITS 10 int digits[3][MAX_DIGITS * 4]; int segments[10][7] = { {1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 1, 0, 1}, {1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 1, 1}, {1, 0, 1, 1, 0, 1, 1}, {1, 0, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 0, 1, 1}, }; void clear_digits_array(void); void print_digits(void); void process_digit(int digit, int position); int main(void) { int d = 0; char c; clear_digits_array(); printf("Enter a number: "); while ((c = getchar()) != '\n') { if (isdigit(c)) { process_digit(atoi(&c), d++); if (d == 10) break; } } print_digits(); return 0; } void clear_digits_array(void) { for (int i = 0; i < 3; i++) for (int j = 0; j < (MAX_DIGITS * 4); j++) digits[i][j] = 0; } void print_digits(void) { for (int j = 0; j < (MAX_DIGITS * 4); j++) digits[0][j] ? putchar('_') : putchar(' '); putchar('\n'); for (int j = 0; j < (MAX_DIGITS * 4); j++) if (digits[1][j]) (j % 2) ? putchar('_') : putchar('|'); else putchar(' '); putchar('\n'); for (int j = 0; j < (MAX_DIGITS * 4); j++) if (digits[2][j]) (j % 2) ? putchar('_') : putchar('|'); else putchar(' '); putchar('\n'); } void process_digit(int digit, int position) { int col_position = position * 4; digits[0][col_position + 1] = segments[digit][0]; digits[1][col_position] = segments[digit][5]; digits[1][col_position + 1] = segments[digit][6]; digits[1][col_position + 2] = segments[digit][1]; digits[2][col_position] = segments[digit][4]; digits[2][col_position + 1] = segments[digit][3]; digits[2][col_position + 2] = segments[digit][2]; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_9/projects/03/03.c
#include <stdio.h> #include <stdlib.h> /* srand(), rand() */ #include <time.h> /* time() */ typedef int Bool; #define SIDE 10 #define DIRECTIONS 4 void generate_random_walk(char board[SIDE][SIDE]); void print_array(char board[SIDE][SIDE]); int main(void) { char board[SIDE][SIDE]; generate_random_walk(board); print_array(board); return 0; } void generate_random_walk(char board[SIDE][SIDE]) { int i, j; char letters[26]; for (i = 0; i < SIDE; i++) { for (j = 0; j < SIDE; j++) printf("%c", board[i][j]); printf("\n"); } int direction, i, j, row = 0, col = 0; Bool up_untried = 1, right_untried = 1, down_untried = 1, left_untried = 1; for (i = 0; i < (int)(sizeof(letters) / sizeof(letters[0])); i++) letters[i] = 'A' + i; for (i = 0; i < SIDE; i++) { for (j = 0; j < SIDE; j++) board[i][j] = '.'; } srand((unsigned)time(NULL)); for (i = 0; i < (int)(sizeof(letters) / sizeof(letters[0])) && (up_untried || right_untried || down_untried || left_untried);) { board[row][col] = letters[i]; direction = rand() % DIRECTIONS; if (direction == 0) { if (row - 1 >= 0 && board[row - 1][col] == '.') row -= 1; else { up_untried = 0; continue; } } if (direction == 1) { if (col + 1 < 10 && board[row][col + 1] == '.') col += 1; else { right_untried = 0; continue; } } if (direction == 2) { if (row + 1 >= 0 && board[row + 1][col] == '.') row += 1; else { down_untried = 0; continue; } } if (direction == 3) { if (col - 1 >= 0 && board[row][col - 1] == '.') col -= 1; else { left_untried = 0; continue; } } i++; up_untried = 1; right_untried = 1; down_untried = 1; left_untried = 1; } } void print_array(char board[SIDE][SIDE]) { int i, j; for (i = 0; i < SIDE; i++) { for (j = 0; j < SIDE; j++) printf("%c", board[i][j]); printf("\n"); } }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/01/01.c
<gh_stars>0 /* Checks numbers for repeated digits */ #include <stdbool.h> /* C99 only */ #include <stdio.h> int main(void) { bool digit_seen[10] = {false}; bool digit_repeated[10] = {false}; int i, digit; long n; printf("Enter a number: "); scanf("%ld", &n); while (n > 0) { digit = n % 10; if (digit_seen[digit]) digit_repeated[digit] = true; digit_seen[digit] = true; n /= 10; } printf("Repeated digit(s): "); for (i = 0; i < 10; i++) { if (digit_seen[i]) printf("%d ", digit_seen[i]); } printf("\n"); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_2/projects/03/03.c
#include <stdio.h> int main(void) { int radius; float volume; printf("Provide the radius of the sphere in meters: "); scanf("%d", &radius); volume = (4.0f / 3.0f) * 3.141592 * (radius * radius * radius); printf("The volume of a shpere with a %d-meter radius is: %f", radius, volume); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_4/projects/03/03.c
#include <stdio.h> int main(void) { int digit_1, digit_2; printf("Enter a two-digit number:"); scanf("%1d%1d", &digit_1, &digit_2); printf("The reversal is: %d%d", digit_2, digit_1); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
test.c
#include <stdio.h> #define SENTENCE_LENGTH 50 int main(void) { char *p, *q, c, terminal, sentence[SENTENCE_LENGTH] = {0}; printf("Enter a sentence: "); for (p = sentence; (c = getchar()) != '\n'; p++) { if (c == '.' || c == '?' || c == '!') { terminal = c; break; } else *p = c; } printf("Reversal of sentence: "); p = &sentence[SENTENCE_LENGTH - 1]; for (; p >= sentence; p--) { if (*p == ' ') { for (q = p + 1; *q != ' ' && *q != '\0'; q++) putchar(*q); putchar(' '); } if (p == sentence) for (q = p; *q != ' ' && *q != '\0'; q++) putchar(*q); } putchar(terminal); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_5/projects/03/03.c
<filename>chapter_5/projects/03/03.c /* Calculates a broker's commission */ #include <stdio.h> int main(void) { float commission, rival_commission, total_trade_value, shares_amount, shares_value; printf("Enter the amount of shares traded: "); scanf("%f", &shares_amount); printf("Enter the value per share: "); scanf("%f", &shares_value); total_trade_value = shares_amount * shares_value; if (shares_amount < 2000) rival_commission = 33.00f + .03f * shares_amount; else rival_commission = 33.00f + .02f * shares_amount; if (total_trade_value < 2500.00f) commission = 30.00f + .017f * total_trade_value; else if (total_trade_value < 6250.00f) commission = 56.00f + .0066f * total_trade_value; else if (total_trade_value < 20000.00f) commission = 76.00f + .0034f * total_trade_value; else if (total_trade_value < 50000.00f) commission = 100.00f + .0022f * total_trade_value; else if (total_trade_value < 500000.00f) commission = 155.00f + .0011f * total_trade_value; else commission = 255.00f + .0009f * total_trade_value; if (commission < 39.00f) commission = 39.00f; printf("Commission: $%.2f\n", commission); printf("Rival Commission: $%.2f\n", rival_commission); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/08/8.c
<filename>chapter_13/projects/08/8.c #include <stdio.h> #include <ctype.h> int compute_scrabble_value(const char *word); int main(void) { int sum; char word[81]; printf("Enter a word: "); scanf("%s", word); printf("Scrabble value: %d\n", compute_scrabble_value(word)); return 0; } int compute_scrabble_value(const char *word) { int sum = 0, values[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10}; while (*word) sum += values[toupper(*word++) - 'A']; return sum; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/08/08.c
#include <stdio.h> int main(void) { int num_of_days, offset_days, starting_day, i; printf("Enter number of days in month: "); scanf("%d", &num_of_days); printf("Enter starting day of the week (1=Mon, 7=Sun): "); scanf("%d", &starting_day); offset_days = starting_day - 1; printf("\n\nMon Tue Wed Thu Fri Sat Sun\n"); for (i = 1; i <= offset_days; i++) { printf(" "); } for (i = 1; i <= num_of_days; i++) { printf("%3d", i); if ((i + offset_days) % 7 == 0) printf("\n"); else printf(" "); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/14/14.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> #include <ctype.h> /* toupper, isalpha */ #include <stdbool.h> /* C99+ only */ bool are_anagrams(const char *word1, const char *word2); int main(void) { char c, word1[80], word2[80], *p; p = word1; printf("Enter first word: "); while ((c = getchar()) != '\n' && p < word1 + 80) { if (isalpha(c)) { *p = toupper(c); p++; } } p = '\0'; p = word2; printf("Enter second word: "); while ((c = getchar()) != '\n' && p < word2 + 80) { if (isalpha(c)) { *p = toupper(c); p++; } } p = '\0'; if (are_anagrams(word1, word2)) { printf("The words are anagrams.\n"); return 0; } printf("The words are not anagrams.\n"); return 0; } bool are_anagrams(const char *word1, const char *word2) { int letters[26] = {0}; int *p = letters; while (*word1) { letters[*word1 - 'A']++; word1++; } while (*word2) { letters[*word2 - 'A']--; word2++; } while (*p) { if (*p != 0) return false; p++; } return true; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_9/projects/08/08.c
#include <stdio.h> #include <stdlib.h> /* srand(), rand() */ #include <time.h> /* time() */ #include <ctype.h> /* toupper() */ int play_game(void); int roll_dice(void); #define DICE_SIDES 6 #define PLAY_AGAIN 'Y' int main(void) { int outcome, wins = 0, losses = 0; char play_again = PLAY_AGAIN; srand((unsigned)time(NULL)); while (toupper(play_again) == PLAY_AGAIN) { outcome = play_game(); if (outcome) { wins++; printf("You win!"); } else { losses++; printf("You lose!"); } printf("\n\nPlay again? "); scanf(" %c", &play_again); } printf("\nWins: %d Losses: %d", wins, losses); return 0; } int play_game(void) { int roll, point = 0; roll = roll_dice(); printf("You rolled: %d\n", roll); if (roll == 7 || roll == 11) return 1; if (roll == 2 || roll == 3 || roll == 12) return 0; point = roll; printf("Your point is %d\n", point); for (;;) { roll = roll_dice(); printf("You rolled %d\n", roll); if (roll == point) return 1; if (roll == 7) { return 0; } } } int roll_dice(void) { int dice_1, dice_2; dice_1 = rand() % DICE_SIDES + 1; dice_2 = rand() % DICE_SIDES + 1; return dice_1 + dice_2; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/16/16.c
#include <stdio.h> #include <ctype.h> int main(void) { char c; int is_anagram = 1; int alphabet[26] = {0}; printf("Enter first word: "); for (int i = 0; (c = getchar()) != '\n'; i++) if (isalpha(c)) alphabet[tolower(c) - 'a']++; printf("Enter second word: "); for (int i = 0; (c = getchar()) != '\n'; i++) if (isalpha(c)) alphabet[tolower(c) - 'a']--; for (int i = 0; i < sizeof(alphabet) / sizeof(alphabet[0]); i++) if (alphabet[i] != 0) { is_anagram = 0; break; } if (is_anagram) printf("The words are anagrams."); else printf("The words are not anagrams."); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/17/17.c
<gh_stars>0 #include <stdio.h> int main(void) { int magic_square_side = 0; int max_side_index, row, col, next_row, next_col; int square[99][99] = {0}; printf("Enter size of magic square: "); scanf("%d", &magic_square_side); max_side_index = magic_square_side - 1; row = 0; col = max_side_index / 2; for (int i = 1; i < (magic_square_side * magic_square_side) + 1; i++) { square[row][col] = i; next_row = (row) ? row - 1 : max_side_index; next_col = (col == max_side_index) ? 0 : col + 1; if (square[next_row][next_col] != 0) row = (row == max_side_index) ? 0 : row + 1; else { row = next_row; col = next_col; } } for (int r = 0; r < magic_square_side; r++) { for (int c = 0; c < magic_square_side; c++) printf("%5d", square[r][c]); printf("\n"); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_8/projects/07/07.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> #define MAX_COL 5 #define MAX_ROW 5 int main(void) { int matrix[MAX_ROW][MAX_COL], i, j, total; for (i = 0; i < MAX_ROW; i++) { printf("Enter row %d: ", i + 1); for (j = 0; j < MAX_COL; j++) { scanf("%d", &matrix[i][j]); } } printf("\nRow totals:"); for (i = 0; i < MAX_ROW; i++) { for (total = 0, j = 0; j < MAX_COL; j++) { total += matrix[i][j]; } printf(" %d", total); } printf("\nColumn totals:"); for (i = 0; i < MAX_COL; i++) { for (total = 0, j = 0; j < MAX_COL; j++) { total += matrix[j][i]; } printf(" %d", total); } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_3/projects/04/04.c
#include <stdio.h> int main(void) { int phone_number_group_1, phone_number_group_2, phone_number_group_3; printf("Enter phone number: [(xxx) xxx-xxxx]: "); scanf("(%d )%d -%d", &phone_number_group_1, &phone_number_group_2, &phone_number_group_3); printf("You entered %d.%d.%d", phone_number_group_1, phone_number_group_2, phone_number_group_3); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_11/projects/03/03.c
#include <stdio.h> void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator); int main(void) { int numerator, denominator, ; printf("Enter a fraction: "); scanf("%d/%d", &numerator, &denominator); reduce(numerator, denominator, &numerator, &denominator); printf("In lowest terms: %d/%d", numerator, denominator); return 0; } void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator) { int a = numerator; int b = denominator; int temp, gcd; for (;;) { if (a == 0) { gcd = b; break; } if (b == 0) { gcd = a; break; } temp = b; b = a % b; a = temp; } *reduced_denominator = numerator / gcd; *reduced_denominator = denominator / gcd; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_3/projects/05/05.c
<gh_stars>0 #include <stdio.h> int main(void) { int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n13, n12, n14, n15, n16; printf("Enter numbers from 1 to 16 in any order:\n"); scanf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &n1, &n2, &n3, &n4, &n5, &n6, &n7, &n8, &n9, &n10, &n11, &n13, &n12, &n14, &n15, &n16); printf("\n%2d %2d %2d %2d\n", n1, n2, n3, n4); printf("%2d %2d %2d %2d\n", n5, n6, n7, n8); printf("%2d %2d %2d %2d\n", n9, n10, n11, n13); printf("%2d %2d %2d %2d\n", n12, n14, n15, n16); printf("\nRow sums: %d %d %d %d", (n1 + n2 + n3 + n4), (n5 + n6 + n7 + n8), (n9 + n10 + n11 + n12), (n13 + n14 + n15 + n16)); printf("\nColumn sums: %d %d %d %d", (n1 + n5 + n9 + n12), (n2 + n6 + n10 + n14), (n3 + n7 + n11 + n15), (n4 + n8 + n12 + n16)); printf("\nDiagonal sums: %d %d", (n1 + n6 + n11 + n16), (n12 + n10 + n7 + n4)); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_6/projects/12/12.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> int main(void) { int n, i, factorial_i; float e, epsilon, current_term; printf("Please enter a number: "); scanf("%d", &n); for (e = 1.00f, factorial_i = 1, i = 1; current_term >= epsilon; ++i) { factorial_i *= i; current_term = 1.00f / factorial_i; e += current_term; } printf("e: %f", e); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_13/projects/18/18.c
#include <stdio.h> int main(void) { int m, d, y; char *months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; printf("Enter a date (mm/dd/yyyy): "); scanf("%d / %d / %d", &m, &d, &y); printf("You entered the date %s %.2d, %d\n", months[m-1], d, y); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_7/projects/07/07.c
/* Adds two fractions */ #include <stdio.h> int main(void) { int num1, denom1, num2, denom2, result_num, result_denom; char operator; printf("Enter two fractions separated by an operator (* / + or -): "); scanf("%d /%d %c %d /%d", &num1, &denom1, &operator, & num2, &denom2); switch (operator) { case '*': { printf("Result: %d/%d\n", num1 * num2, denom1 * denom2); break; } case '/': { printf("Result: %d/%d\n", num1 * denom2, num2 * denom1); break; } case '+': { printf("Result: %d/%d\n", (num1 * denom2) + (num2 * denom1), denom1 * denom2); break; } case '-': { printf("Result: %d/%d\n", (num1 * denom2) - (num2 * denom1), denom1 * denom2); break; } default: printf("Operation %c not supported.\n", operator); return 1; /* operation error */ } return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_2/projects/02/02.c
#include <stdio.h> int main(void) { int radius; float volume; radius = 10; volume = (4.0f / 3.0f) * 3.141592 * (radius * radius * radius); printf("The volume of a shpere with a 10-meter radius is: %f", volume); return 0; }
reinvanimschoot/c-programming-a-modern-approach-solutions
chapter_5/projects/05/05.c
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions #include <stdio.h> int main(void) { float taxable_amount, income_tax; printf("Please enter the taxable amount: "); scanf("%f", &taxable_amount); if (taxable_amount < 750.0f) income_tax = taxable_amount * .01f; else if (taxable_amount < 2250.00f) income_tax = 7.50f + ((taxable_amount - 750.00f) * .02f); else if (taxable_amount < 3750.00f) income_tax = 37.50f + ((taxable_amount - 2250.00f) * .03f); else if (taxable_amount < 5250.00f) income_tax = 82.50f + ((taxable_amount - 3750.00f) * .04f); else if (taxable_amount < 7000.00f) income_tax = 142.50f + ((taxable_amount - 5250.00f) * .05f); else income_tax = 230.50f + ((taxable_amount - 7000.00f) * .06f); printf("The tax due is: %.2f", taxable_amount); }