globle void gensystem( void *theEnv) { char *commandBuffer = NULL; int bufferPosition = 0; unsigned bufferMaximum = 0; int numa, i; DATA_OBJECT tempValue; char *theString; /*===========================================*/ /* Check for the corret number of arguments. */ /*===========================================*/ if ((numa = EnvArgCountCheck(theEnv,"system",AT_LEAST,1)) == -1) return; /*============================================================*/ /* Concatenate the arguments together to form a single string */ /* containing the command to be sent to the operating system. */ /*============================================================*/ for (i = 1 ; i <= numa; i++) { EnvRtnUnknown(theEnv,i,&tempValue); if ((GetType(tempValue) != STRING) && (GetType(tempValue) != SYMBOL)) { SetHaltExecution(theEnv,TRUE); SetEvaluationError(theEnv,TRUE); ExpectedTypeError2(theEnv,"system",i); return; } theString = DOToString(tempValue); commandBuffer = AppendToString(theEnv,theString,commandBuffer,&bufferPosition,&bufferMaximum); } if (commandBuffer == NULL) return; /*=======================================*/ /* Execute the operating system command. */ /*=======================================*/ #if VAX_VMS if (SystemDependentData(theEnv)->PauseEnvFunction != NULL) (*SystemDependentData(theEnv)->PauseEnvFunction)(theEnv); VMSSystem(commandBuffer); putchar('\n'); if (SystemDependentData(theEnv)->ContinueEnvFunction != NULL) (*SystemDependentData(theEnv)->ContinueEnvFunction)(theEnv,1); if (SystemDependentData(theEnv)->RedrawScreenFunction != NULL) (*SystemDependentData(theEnv)->RedrawScreenFunction)(theEnv); #endif #if UNIX_7 || UNIX_V || IBM_MSC || IBM_TBC || IBM_ICB || IBM_ZTC || IBM_SC || IBM_MCW || IBM_GCC if (SystemDependentData(theEnv)->PauseEnvFunction != NULL) (*SystemDependentData(theEnv)->PauseEnvFunction)(theEnv); system(commandBuffer); if (SystemDependentData(theEnv)->ContinueEnvFunction != NULL) (*SystemDependentData(theEnv)->ContinueEnvFunction)(theEnv,1); if (SystemDependentData(theEnv)->RedrawScreenFunction != NULL) (*SystemDependentData(theEnv)->RedrawScreenFunction)(theEnv); #else #if ! VAX_VMS EnvPrintRouter(theEnv,WDIALOG, "System function not fully defined for this system.\n"); #endif #endif /*==================================================*/ /* Return the string buffer containing the command. */ /*==================================================*/ rm(theEnv,commandBuffer,bufferMaximum); return; }
void output_listing(char *ifilename) { char buf[1024]; FILE *ifile; struct instruction *cur_instr; patch_t *cur_patch; symbol_node_t *cur_func; int *func_values; int instrcount; int instrptr; unsigned int line; int func_count; int skip_addr; instrcount = 0; instrptr = 0; line = 1; skip_addr = 0; if ((ifile = fopen(ifilename, "r")) == NULL) { perror(ifilename); stop(NULL, EX_DATAERR); } /* * Determine which options to apply to this listing. */ for (func_count = 0, cur_func = SLIST_FIRST(&patch_functions); cur_func != NULL; cur_func = SLIST_NEXT(cur_func, links)) func_count++; func_values = NULL; if (func_count != 0) { func_values = (int *)malloc(func_count * sizeof(int)); if (func_values == NULL) stop("Could not malloc", EX_OSERR); func_values[0] = 0; /* FALSE func */ func_count--; /* * Ask the user to fill in the return values for * the rest of the functions. */ for (cur_func = SLIST_FIRST(&patch_functions); cur_func != NULL && SLIST_NEXT(cur_func, links) != NULL; cur_func = SLIST_NEXT(cur_func, links), func_count--) { int input; fprintf(stdout, "\n(%s)\n", cur_func->symbol->name); fprintf(stdout, "Enter the return value for " "this expression[T/F]:"); while (1) { input = getchar(); input = toupper(input); if (input == 'T') { func_values[func_count] = 1; break; } else if (input == 'F') { func_values[func_count] = 0; break; } } if (isatty(fileno(stdin)) == 0) putchar(input); } fprintf(stdout, "\nThanks!\n"); } /* Now output the listing */ cur_patch = STAILQ_FIRST(&patches); for (cur_instr = STAILQ_FIRST(&seq_program); cur_instr != NULL; cur_instr = STAILQ_NEXT(cur_instr, links), instrcount++) { if (check_patch(&cur_patch, instrcount, &skip_addr, func_values) == 0) { /* Don't count this instruction as it is in a patch * that was removed. */ continue; } while (line < cur_instr->srcline) { fgets(buf, sizeof(buf), ifile); fprintf(listfile, " \t%s", buf); line++; } fprintf(listfile, "%04x %02x%02x%02x%02x", instrptr, #if BYTE_ORDER == LITTLE_ENDIAN cur_instr->format.bytes[0], cur_instr->format.bytes[1], cur_instr->format.bytes[2], cur_instr->format.bytes[3]); #else cur_instr->format.bytes[3], cur_instr->format.bytes[2], cur_instr->format.bytes[1], cur_instr->format.bytes[0]); #endif /* * Macro expansions can cause several instructions * to be output for a single source line. Only * advance the line once in these cases. */ if (line == cur_instr->srcline) { fgets(buf, sizeof(buf), ifile); fprintf(listfile, "\t%s", buf); line++; } else { fprintf(listfile, "\n"); } instrptr++; } free(func_values); /* Dump the remainder of the file */ while(fgets(buf, sizeof(buf), ifile) != NULL) fprintf(listfile, " %s", buf); fclose(ifile); }
void tcp_print(register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct tcphdr *tp; register const struct ip *ip; register u_char flags; register int hlen; register char ch; register struct tcp_seq_hash *th = NULL; register int rev = 0; u_int16_t sport, dport, win, urp; tcp_seq seq, ack; #ifdef INET6 register const struct ip6_hdr *ip6; #endif tp = (struct tcphdr *)bp; switch (((struct ip *)bp2)->ip_v) { case 4: ip = (struct ip *)bp2; #ifdef INET6 ip6 = NULL; #endif break; #ifdef INET6 case 6: ip = NULL; ip6 = (struct ip6_hdr *)bp2; break; #endif default: (void)printf("invalid ip version"); return; } ch = '\0'; if (length < sizeof(*tp)) { (void)printf("truncated-tcp %d", length); return; } if (!TTEST(tp->th_dport)) { #ifdef INET6 if (ip6) { (void)printf("%s > %s: [|tcp]", ip6addr_string(&ip6->ip6_src), ip6addr_string(&ip6->ip6_dst)); } else #endif /*INET6*/ { (void)printf("%s > %s: [|tcp]", ipaddr_string(&ip->ip_src), ipaddr_string(&ip->ip_dst)); } return; } sport = ntohs(tp->th_sport); dport = ntohs(tp->th_dport); #ifdef INET6 if (ip6) { if (ip6->ip6_nxt == IPPROTO_TCP) { (void)printf("%s.%s > %s.%s: ", ip6addr_string(&ip6->ip6_src), tcpport_string(sport), ip6addr_string(&ip6->ip6_dst), tcpport_string(dport)); } else { (void)printf("%s > %s: ", tcpport_string(sport), tcpport_string(dport)); } } else #endif /*INET6*/ { if (ip->ip_p == IPPROTO_TCP) { (void)printf("%s.%s > %s.%s: ", ipaddr_string(&ip->ip_src), tcpport_string(sport), ipaddr_string(&ip->ip_dst), tcpport_string(dport)); } else { (void)printf("%s > %s: ", tcpport_string(sport), tcpport_string(dport)); } } if (!qflag && TTEST(tp->th_seq) && !TTEST(tp->th_ack)) (void)printf("%u ", ntohl(tp->th_seq)); TCHECK(*tp); seq = ntohl(tp->th_seq); ack = ntohl(tp->th_ack); win = ntohs(tp->th_win); urp = ntohs(tp->th_urp); hlen = tp->th_off * 4; if (qflag) { (void)printf("tcp %d", length - tp->th_off * 4); return; } else if (packettype != PT_TCP) { /* * If data present and NFS port used, assume NFS. * Pass offset of data plus 4 bytes for RPC TCP msg length * to NFS print routines. */ u_int len = length - hlen; if ((u_char *)tp + 4 + sizeof(struct rpc_msg) <= snapend && dport == NFS_PORT) { nfsreq_print((u_char *)tp + hlen + 4, len, (u_char *)ip); return; } else if ((u_char *)tp + 4 + sizeof(struct rpc_msg) <= snapend && sport == NFS_PORT) { nfsreply_print((u_char *)tp + hlen + 4, len, (u_char *)ip); return; } } if ((flags = tp->th_flags) & (TH_SYN|TH_FIN|TH_RST|TH_PUSH| TH_ECNECHO|TH_CWR)) { if (flags & TH_SYN) putchar('S'); if (flags & TH_FIN) putchar('F'); if (flags & TH_RST) putchar('R'); if (flags & TH_PUSH) putchar('P'); if (flags & TH_CWR) putchar('W'); /* congestion _W_indow reduced (ECN) */ if (flags & TH_ECNECHO) putchar('E'); /* ecn _E_cho sent (ECN) */ } else putchar('.'); if (!Sflag && (flags & TH_ACK)) { struct tha tha; /* * Find (or record) the initial sequence numbers for * this conversation. (we pick an arbitrary * collating order so there's only one entry for * both directions). */ #ifdef INET6 bzero(&tha, sizeof(tha)); rev = 0; if (ip6) { if (sport > dport) { rev = 1; } else if (sport == dport) { int i; for (i = 0; i < 4; i++) { if (((u_int32_t *)(&ip6->ip6_src))[i] > ((u_int32_t *)(&ip6->ip6_dst))[i]) { rev = 1; break; } } } if (rev) { tha.src = ip6->ip6_dst; tha.dst = ip6->ip6_src; tha.port = dport << 16 | sport; } else { tha.dst = ip6->ip6_dst; tha.src = ip6->ip6_src; tha.port = sport << 16 | dport; } } else { if (sport > dport || (sport == dport && ip->ip_src.s_addr > ip->ip_dst.s_addr)) { rev = 1; } if (rev) { *(struct in_addr *)&tha.src = ip->ip_dst; *(struct in_addr *)&tha.dst = ip->ip_src; tha.port = dport << 16 | sport; } else { *(struct in_addr *)&tha.dst = ip->ip_dst; *(struct in_addr *)&tha.src = ip->ip_src; tha.port = sport << 16 | dport; } } #else if (sport < dport || (sport == dport && ip->ip_src.s_addr < ip->ip_dst.s_addr)) { tha.src = ip->ip_src, tha.dst = ip->ip_dst; tha.port = sport << 16 | dport; rev = 0; } else { tha.src = ip->ip_dst, tha.dst = ip->ip_src; tha.port = dport << 16 | sport; rev = 1; } #endif for (th = &tcp_seq_hash[tha.port % TSEQ_HASHSIZE]; th->nxt; th = th->nxt) if (!memcmp((char *)&tha, (char *)&th->addr, sizeof(th->addr))) break; if (!th->nxt || flags & TH_SYN) { /* didn't find it or new conversation */ if (th->nxt == NULL) { th->nxt = (struct tcp_seq_hash *) calloc(1, sizeof(*th)); if (th->nxt == NULL) error("tcp_print: calloc"); } th->addr = tha; if (rev) th->ack = seq, th->seq = ack - 1; else th->seq = seq, th->ack = ack - 1; } else { if (rev) seq -= th->ack, ack -= th->seq; else seq -= th->seq, ack -= th->ack; } } hlen = tp->th_off * 4; if (hlen > length) { (void)printf(" [bad hdr length]"); return; } if (ip && ip->ip_v == 4 && vflag) { int sum; if (TTEST2(tp->th_sport, length)) { sum = tcp_cksum(ip, tp, length); if (sum != 0) (void)printf(" [bad tcp cksum %x!]", sum); else (void)printf(" [tcp sum ok]"); } } #ifdef INET6 if (ip6 && ip6->ip6_plen && vflag) { int sum; if (TTEST2(tp->th_sport, length)) { sum = tcp6_cksum(ip6, tp, length); if (sum != 0) (void)printf(" [bad tcp cksum %x!]", sum); else (void)printf(" [tcp sum ok]"); } } #endif /* OS Fingerprint */ if (oflag && (flags & (TH_SYN|TH_ACK)) == TH_SYN) { struct pf_osfp_enlist *head = NULL; struct pf_osfp_entry *fp; unsigned long left; left = (unsigned long)(snapend - (const u_char *)tp); if (left >= hlen) head = pf_osfp_fingerprint_hdr(ip, ip6, tp); if (head) { int prev = 0; printf(" (src OS:"); SLIST_FOREACH(fp, head, fp_entry) { if (fp->fp_enflags & PF_OSFP_EXPANDED) continue; if (prev) printf(","); printf(" %s", fp->fp_class_nm); if (fp->fp_version_nm[0]) printf(" %s", fp->fp_version_nm); if (fp->fp_subtype_nm[0]) printf(" %s", fp->fp_subtype_nm); prev = 1; } printf(")"); } else { if (left < hlen) printf(" (src OS: short-pkt)"); else printf(" (src OS: unknown)"); } }
int pstatus (char *arg) { struct ioc_vol v; struct ioc_read_subchannel ss; struct cd_sub_channel_info data; int rc, trk, m, s, f; int what = 0; char *p, vmcn[(4 * 15) + 1]; while ((p = strtok(arg, " \t"))) { arg = 0; if (!strncasecmp(p, "audio", strlen(p))) what |= STATUS_AUDIO; else if (!strncasecmp(p, "media", strlen(p))) what |= STATUS_MEDIA; else if (!strncasecmp(p, "volume", strlen(p))) what |= STATUS_VOLUME; else { warnx("invalid command arguments"); return 0; } } if (!what) what = STATUS_AUDIO|STATUS_MEDIA|STATUS_VOLUME; if (what & STATUS_AUDIO) { rc = status (&trk, &m, &s, &f); if (rc >= 0) if (verbose) printf ("Audio status = %d<%s>, current track = %d, current position = %d:%02d.%02d\n", rc, strstatus (rc), trk, m, s, f); else printf ("%d %d %d:%02d.%02d\n", rc, trk, m, s, f); else printf ("No current status info available\n"); } if (what & STATUS_MEDIA) { bzero (&ss, sizeof (ss)); ss.data = &data; ss.data_len = sizeof (data); ss.address_format = msf ? CD_MSF_FORMAT : CD_LBA_FORMAT; ss.data_format = CD_MEDIA_CATALOG; rc = ioctl (fd, CDIOCREADSUBCHANNEL, (char *) &ss); if (rc >= 0) { printf("Media catalog is %sactive", ss.data->what.media_catalog.mc_valid ? "": "in"); if (ss.data->what.media_catalog.mc_valid && ss.data->what.media_catalog.mc_number[0]) { strvisx (vmcn, ss.data->what.media_catalog.mc_number, (sizeof (vmcn) - 1) / 4, VIS_OCTAL | VIS_NL); printf(", number \"%.*s\"", (int)sizeof (vmcn), vmcn); } putchar('\n'); } else printf("No media catalog info available\n"); } if (what & STATUS_VOLUME) { rc = ioctl (fd, CDIOCGETVOL, &v); if (rc >= 0) if (verbose) printf ("Left volume = %d, right volume = %d\n", v.vol[0], v.vol[1]); else printf ("%d %d\n", v.vol[0], v.vol[1]); else printf ("No volume level info available\n"); } return(0); }
int main(int argc, char *argv[]) { const struct cmd *c; fcntl(3, F_CLOSEM); openlog("timedc", 0, LOG_AUTH); /* * security dictates! */ if (priv_resources() < 0) errx(EXIT_FAILURE, "Could not get privileged resources"); if (drop_privileges() < 0) errx(EXIT_FAILURE, "Could not drop privileges"); if (--argc > 0) { c = getcmd(*++argv); if (c == (struct cmd *)-1) { printf("?Ambiguous command\n"); exit(EXIT_FAILURE); } if (c == 0) { printf("?Invalid command\n"); exit(EXIT_FAILURE); } (*c->c_handler)(argc, argv); exit(EXIT_SUCCESS); } fromatty = isatty(fileno(stdin)); if (setjmp(toplevel)) putchar('\n'); (void) signal(SIGINT, intr); for (;;) { if (fromatty) { printf("timedc> "); (void) fflush(stdout); } if (fgets(cmdline, sizeof(cmdline), stdin) == NULL) quit(0, NULL); if (cmdline[0] == 0) break; if (makeargv()) { printf("?Too many arguments\n"); continue; } if (margv[0] == 0) continue; c = getcmd(margv[0]); if (c == (struct cmd *)-1) { printf("?Ambiguous command\n"); continue; } if (c == 0) { printf("?Invalid command\n"); continue; } (*c->c_handler)(margc, margv); } return 0; }
int main() { int c = getchar(); do { int d = c; switch (c) { case '1': d = '`'; break; case '2': d = '1'; break; case '3': d = '2'; break; case '4': d = '3'; break; case '5': d = '4'; break; case '6': d = '5'; break; case '7': d = '6'; break; case '8': d = '7'; break; case '9': d = '8'; break; case '0': d = '9'; break; case '-': d = '0'; break; case '=': d = '-'; break; case 'W': d = 'Q'; break; case 'E': d = 'W'; break; case 'R': d = 'E'; break; case 'T': d = 'R'; break; case 'Y': d = 'T'; break; case 'U': d = 'Y'; break; case 'I': d = 'U'; break; case 'O': d = 'I'; break; case 'P': d = 'O'; break; case '[': d = 'P'; break; case ']': d = '['; break; case '\\': d = ']'; break; case 'S': d = 'A'; break; case 'D': d = 'S'; break; case 'F': d = 'D'; break; case 'G': d = 'F'; break; case 'H': d = 'G'; break; case 'J': d = 'H'; break; case 'K': d = 'J'; break; case 'L': d = 'K'; break; case ';': d = 'L'; break; case '\'': d = ';'; break; case 'X': d = 'Z'; break; case 'C': d = 'X'; break; case 'V': d = 'C'; break; case 'B': d = 'V'; break; case 'N': d = 'B'; break; case 'M': d = 'N'; break; case ',': d = 'M'; break; case '.': d = ','; break; case '/': d = '.'; break; } putchar(d); c = getchar(); } while (c != EOF); return 0; }
int main(int argc, char *argv[]) { int c; /* Character */ FILE *fp; /* File pointer */ fp=fopen(argv[1],"r"); /* Open file */ printf("/*\n"); printf("####################################\n"); printf("#\n"); printf("# --- MAKE-C-TPL-0001.C ---\n"); printf("#\n"); printf("# This file named %s has been\n", argv[1]); printf("# converted to a C Template file.\n"); printf("#\n"); printf("####################################\n"); printf("*/\n\n"); printf("/*\n"); printf("===========================================================\n"); printf("----- %s -----\n", argv[1]); printf("\n"); printf("Written in ISO/IEC 9899:2011 standard C\n"); printf("===========================================================\n"); printf("*/\n"); printf("\n"); printf("/* ----- Header files ----- */\n"); printf("#include <stdio.h>\n"); printf("#include <stdlib.h>\n\n"); printf("/* ----- Typedefs, structs and unions ----- */\n\n"); printf("/* ----- Function Prototypes ----- */\n\n"); printf("/* ----- Global variables ----- */\n\n"); printf("/* ----- Program starts here ----- */\n"); printf("int main(int argc, char *argv[])\n"); printf("{\n"); printf(" printf(\""); /* Open first printf statement */ while (c != EOF) /* Loop until the end of the file */ { c=fgetc(fp); /* Get a character from the file */ if (c == '\\') /* Backslash */ { printf("\\\\"); } else if (c == '%') /* Percent sign */ { printf("%%%%"); } else if (c == '\'') /* Single quote */ { printf("\\\'"); } else if (c == '\"') /* Double quotes */ { printf("\\\""); } else if (c == '\?') /* Question mark */ { printf("\\?"); } else if (c == '\t') /* Tabs */ { printf("\\t"); } else if (c == '\f') /* Form feeds */ { printf("\\f"); } else if (c == '\a') /* Bell */ { printf("\\a"); } else if (c == '\b') /* Backspace */ { printf("\\b"); } else if (c == '\v') /* Vertical tabs */ { printf("\\v"); } else if (c >= 127) /* Characters 127 to 255 */ { printf("\\x%02X", c); } else if (c == '\n') /* Newline */ { printf("\\n\");\n"); /* Close printf statement */ printf(" printf(\""); /* Open next printf statement */ } else if (c == EOF) /* End of file */ { printf("\\n\");\n\n"); /* Close final printf statement and exit */ break; } else putchar(c); } printf(" return 0;\n"); printf("}\n\n"); fclose(fp); return 0; }
void show_n_char(char ch, int num) { int count; for (count=1; count<=num; count++) putchar(ch); }
int main() { zdd_init(); // The universe is {1, ..., 9^3 = 729}. zdd_set_vmax(729); // Number rows and columns from 0. Digits are integers [1..9]. // The digit d at (r, c) is represented by element 81 r + 9 c + d. inta_t list; inta_init(list); for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { int c = getchar(); if (EOF == c) die("unexpected EOF"); if ('\n' == c) die("unexpected newline"); if (c >= '1' && c <= '9') { inta_append(list, 81 * i + 9 * j + c - '0'); } } int c = getchar(); if (EOF == c) die("unexpected EOF"); if ('\n' != c) die("expected newline"); } inta_append(list, -1); contains_all(inta_raw(list)); inta_clear(list); global_one_digit_per_box(); zdd_intersection(); // Number of ways you can put nine 1s into a sudoku is // 9*6*3*6*3*4*2*2. printf("rows\n"); fflush(stdout); for(int i = 1; i <= 9; i++) { for(int r = 0; r < 9; r++) { unique_digit_per_row(i, r); if (r) zdd_intersection(); } zdd_intersection(); } for(int i = 1; i <= 9; i++) { for(int c = 0; c < 3; c++) { for(int r = 0; r < 3; r++) { printf("3x3 %d: %d, %d\n", i, r, c); fflush(stdout); unique_digit_per_3x3(i, r, c); if (r) zdd_intersection(); } if (c) zdd_intersection(); } zdd_intersection(); } for(int i = 1; i <= 9; i++) { for(int c = 0; c < 9; c++) { printf("cols %d: %d\n", i, c); fflush(stdout); unique_digit_per_col(i, c); if (c) zdd_intersection(); } zdd_intersection(); } void printsol(int *v, int vcount) { for(int i = 0; i < vcount; i++) { putchar(((v[i] - 1) % 9) + '1'); if (8 == (i % 9)) putchar('\n'); } putchar('\n'); } zdd_forall(printsol); return 0; }
void print_chr(char c) {putchar(c);}
void __io_putchar(char c) { putchar(c); }
int downloadFile(){ putchar('\n'); return download("http://dl.nwjs.io/v0.12.3/chromedriver-nw-v0.12.3-linux-x64.tar.gz", "test-data/downloadedFile", downloadCb) == DOWNLOAD_SUCCESS; }
int main(int argc, char **argv) { register int op; bpf_u_int32 localnet, netmask; register char *cp, *cmdbuf, *device; int doselect, dopoll, dotimeout, dononblock; struct bpf_program fcode; char ebuf[PCAP_ERRBUF_SIZE]; pcap_if_t *devlist; int selectable_fd; int status; int packet_count; device = NULL; doselect = 0; dopoll = 0; dotimeout = 0; dononblock = 0; if ((cp = strrchr(argv[0], '/')) != NULL) program_name = cp + 1; else program_name = argv[0]; opterr = 0; while ((op = getopt(argc, argv, "i:sptn")) != -1) { switch (op) { case 'i': device = optarg; break; case 's': doselect = 1; break; case 'p': dopoll = 1; break; case 't': dotimeout = 1; break; case 'n': dononblock = 1; break; default: usage(); /* NOTREACHED */ } } if (doselect && dopoll) { fprintf(stderr, "selpolltest: choose select (-s) or poll (-p), but not both\n"); return 1; } if (dotimeout && !doselect && !dopoll) { fprintf(stderr, "selpolltest: timeout (-t) requires select (-s) or poll (-p)\n"); return 1; } if (device == NULL) { if (pcap_findalldevs(&devlist, ebuf) == -1) error("%s", ebuf); if (devlist == NULL) error("no interfaces available for capture"); device = strdup(devlist->name); pcap_freealldevs(devlist); } *ebuf = '\0'; pd = pcap_open_live(device, 65535, 0, 1000, ebuf); if (pd == NULL) error("%s", ebuf); else if (*ebuf) warning("%s", ebuf); if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) { localnet = 0; netmask = 0; warning("%s", ebuf); } cmdbuf = copy_argv(&argv[optind]); if (pcap_compile(pd, &fcode, cmdbuf, 1, netmask) < 0) error("%s", pcap_geterr(pd)); if (pcap_setfilter(pd, &fcode) < 0) error("%s", pcap_geterr(pd)); if (pcap_get_selectable_fd(pd) == -1) error("pcap_get_selectable_fd() fails"); if (dononblock) { if (pcap_setnonblock(pd, 1, ebuf) == -1) error("pcap_setnonblock failed: %s", ebuf); } selectable_fd = pcap_get_selectable_fd(pd); printf("Listening on %s\n", device); if (doselect) { for (;;) { fd_set setread, setexcept; struct timeval seltimeout; FD_ZERO(&setread); FD_SET(selectable_fd, &setread); FD_ZERO(&setexcept); FD_SET(selectable_fd, &setexcept); if (dotimeout) { seltimeout.tv_sec = 0; seltimeout.tv_usec = 1000; status = select(selectable_fd + 1, &setread, NULL, &setexcept, &seltimeout); } else { status = select(selectable_fd + 1, &setread, NULL, &setexcept, NULL); } if (status == -1) { printf("Select returns error (%s)\n", strerror(errno)); } else { if (status == 0) printf("Select timed out: "); else printf("Select returned a descriptor: "); if (FD_ISSET(selectable_fd, &setread)) printf("readable, "); else printf("not readable, "); if (FD_ISSET(selectable_fd, &setexcept)) printf("exceptional condition\n"); else printf("no exceptional condition\n"); packet_count = 0; status = pcap_dispatch(pd, -1, countme, (u_char *)&packet_count); if (status < 0) break; printf("%d packets seen, %d packets counted after select returns\n", status, packet_count); } } } else if (dopoll) { for (;;) { struct pollfd fd; int polltimeout; fd.fd = selectable_fd; fd.events = POLLIN; if (dotimeout) polltimeout = 1; else polltimeout = -1; status = poll(&fd, 1, polltimeout); if (status == -1) { printf("Poll returns error (%s)\n", strerror(errno)); } else { if (status == 0) printf("Poll timed out\n"); else { printf("Poll returned a descriptor: "); if (fd.revents & POLLIN) printf("readable, "); else printf("not readable, "); if (fd.revents & POLLERR) printf("exceptional condition, "); else printf("no exceptional condition, "); if (fd.revents & POLLHUP) printf("disconnect, "); else printf("no disconnect, "); if (fd.revents & POLLNVAL) printf("invalid\n"); else printf("not invalid\n"); } packet_count = 0; status = pcap_dispatch(pd, -1, countme, (u_char *)&packet_count); if (status < 0) break; printf("%d packets seen, %d packets counted after poll returns\n", status, packet_count); } } } else { for (;;) { packet_count = 0; status = pcap_dispatch(pd, -1, countme, (u_char *)&packet_count); if (status < 0) break; printf("%d packets seen, %d packets counted after pcap_dispatch returns\n", status, packet_count); } } if (status == -2) { /* * We got interrupted, so perhaps we didn't * manage to finish a line we were printing. * Print an extra newline, just in case. */ putchar('\n'); } (void)fflush(stdout); if (status == -1) { /* * Error. Report it. */ (void)fprintf(stderr, "%s: pcap_loop: %s\n", program_name, pcap_geterr(pd)); } pcap_close(pd); exit(status == -1 ? 1 : 0); }
/// putchard - putchar that takes a double and returns 0. double putchard(double X) { putchar((char)X); return 0; }
/* * Output termcap entry to stdout, quoting characters that would give the * shell problems and omitting empty fields. */ void wrtermcap(char *bp) { int ch; char *p; char *t, *sep; /* Find the end of the terminal names. */ if ((t = strchr(bp, ':')) == NULL) errx(1, "termcap names not colon terminated"); *t++ = '\0'; /* Output terminal names that don't have whitespace. */ sep = strdup(""); while ((p = strsep(&bp, "|")) != NULL) if (*p != '\0' && strpbrk(p, " \t") == NULL) { (void)printf("%s%s", sep, p); sep = strdup("|"); } (void)putchar(':'); /* * Output fields, transforming any dangerous characters. Skip * empty fields or fields containing only whitespace. */ while ((p = strsep(&t, ":")) != NULL) { while ((ch = *p) != '\0' && isspace(ch)) ++p; if (ch == '\0') continue; while ((ch = *p++) != '\0') switch(ch) { case '\033': (void)printf("\\E"); case ' ': /* No spaces. */ (void)printf("\\040"); break; case '!': /* No csh history chars. */ (void)printf("\\041"); break; case ',': /* No csh history chars. */ (void)printf("\\054"); break; case '"': /* No quotes. */ (void)printf("\\042"); break; case '\'': /* No quotes. */ (void)printf("\\047"); break; case '`': /* No quotes. */ (void)printf("\\140"); break; case '\\': /* Anything following is OK. */ case '^': (void)putchar(ch); if ((ch = *p++) == '\0') break; /* FALLTHROUGH */ default: (void)putchar(ch); } (void)putchar(':'); } }
/* Load and resample XML BSDF description using Klems basis */ static void eval_bsdf(const char *fname) { ANGLE_BASIS *abp = get_basis(kbasis); SDData bsd; SDError ec; FVECT vin, vout; SDValue sv; double sum; int i, j, n; SDclearBSDF(&bsd, fname); /* load BSDF file */ if ((ec = SDloadFile(&bsd, fname)) != SDEnone) goto err; xml_prologue(&bsd); /* pass geometry */ /* front reflection */ if (bsd.rf != NULL || bsd.rLambFront.cieY > .002) { input_orient = 1; output_orient = 1; data_prologue(); for (j = 0; j < abp->nangles; j++) { for (i = 0; i < abp->nangles; i++) { sum = 0; /* average over patches */ for (n = npsamps; n-- > 0; ) { fo_getvec(vout, j+(n+frandom())/npsamps, abp); fi_getvec(vin, i+urand(n), abp); ec = SDevalBSDF(&sv, vout, vin, &bsd); if (ec != SDEnone) goto err; sum += sv.cieY; } printf("\t%.3e\n", sum/npsamps); } putchar('\n'); /* extra space between rows */ } data_epilogue(); } /* back reflection */ if (bsd.rb != NULL || bsd.rLambBack.cieY > .002) { input_orient = -1; output_orient = -1; data_prologue(); for (j = 0; j < abp->nangles; j++) { for (i = 0; i < abp->nangles; i++) { sum = 0; /* average over patches */ for (n = npsamps; n-- > 0; ) { bo_getvec(vout, j+(n+frandom())/npsamps, abp); bi_getvec(vin, i+urand(n), abp); ec = SDevalBSDF(&sv, vout, vin, &bsd); if (ec != SDEnone) goto err; sum += sv.cieY; } printf("\t%.3e\n", sum/npsamps); } putchar('\n'); /* extra space between rows */ } data_epilogue(); } /* front transmission */ if (bsd.tf != NULL || bsd.tLamb.cieY > .002) { input_orient = 1; output_orient = -1; data_prologue(); for (j = 0; j < abp->nangles; j++) { for (i = 0; i < abp->nangles; i++) { sum = 0; /* average over patches */ for (n = npsamps; n-- > 0; ) { bo_getvec(vout, j+(n+frandom())/npsamps, abp); fi_getvec(vin, i+urand(n), abp); ec = SDevalBSDF(&sv, vout, vin, &bsd); if (ec != SDEnone) goto err; sum += sv.cieY; } printf("\t%.3e\n", sum/npsamps); } putchar('\n'); /* extra space between rows */ } data_epilogue(); } /* back transmission */ if ((bsd.tb != NULL) | (bsd.tf != NULL)) { input_orient = -1; output_orient = 1; data_prologue(); for (j = 0; j < abp->nangles; j++) { for (i = 0; i < abp->nangles; i++) { sum = 0; /* average over patches */ for (n = npsamps; n-- > 0; ) { fo_getvec(vout, j+(n+frandom())/npsamps, abp); bi_getvec(vin, i+urand(n), abp); ec = SDevalBSDF(&sv, vout, vin, &bsd); if (ec != SDEnone) goto err; sum += sv.cieY; } printf("\t%.3e\n", sum/npsamps); } putchar('\n'); /* extra space between rows */ } data_epilogue(); } SDfreeBSDF(&bsd); /* all done */ return; err: SDreportError(ec, stderr); exit(1); }
static void print_help() { printf("rsd - version %s - Copyright (C) 2010-2011 Hans-Kristian Arntzen\n", RSD_VERSION); printf("==========================================================================\n"); #ifdef _WIN32 printf("Usage: rsd [ -p/--port | --bind | -R/--rate | -v/--verbose | --debug | -h/--help | -D/--daemon ]\n"); #else #ifdef HAVE_SAMPLERATE printf("Usage: rsd [ -d/--device | -b/--backend | -p/--port | --bind | -R/--rate | -Q/--resampler | -D/--daemon | -v/--verbose | --debug | -h/--help | --single | --kill ]\n"); #else printf("Usage: rsd [ -d/--device | -b/--backend | -p/--port | --bind | -R/--rate | -D/--daemon | -v/--verbose | --debug | -h/--help | --single | --kill ]\n"); #endif #endif printf("\n-d/--device: Specifies a device to use. This is backend specific.\n"); printf(" Examples:\n\t-d hw:1,0\n\t-d /dev/audio\n\t-d system:playback_1,system:playback_2\n\t" " Defaults to \"default\" for alsa and /dev/dsp for OSS\n"); printf("\n-b/--backend: Specifies which audio backend to use.\n"); printf("Supported backends: "); #ifdef _PULSE printf("pulse "); #endif #ifdef _ALSA printf("alsa "); #endif #ifdef _OSS printf("oss "); #endif #ifdef _ROARVS printf("roar "); #endif #ifdef _AO printf("libao "); #endif #ifdef _PORTA printf("portaudio "); #endif #ifdef _JACK printf("jack "); #endif #ifdef _AL printf("openal "); #endif #ifdef _DS printf("dsound "); #endif #ifdef _MUROAR printf("muroar "); #endif #ifdef _COREAUDIO printf("coreaudio "); #endif putchar('\n'); putchar('\n'); printf("-D/--daemon: Runs as daemon.\n"); #ifndef _WIN32 printf("-p/--port: Defines which port to listen on.\n"); printf("--single: Only allows a single connection at a time.\n"); printf("--kill: Cleanly shuts downs the running rsd process.\n"); #endif printf("-R/--rate: Resamples all audio to defined samplerate before sending audio to the audio drivers. Mostly used if audio driver does not provide proper resampling.\n"); #ifdef HAVE_SAMPLERATE printf("-Q/--resampler: Value from 1 (worst) to 5 (best) (default: 3) defines quality of libsamplerate resampling.\n"); #endif #ifdef HAVE_SYSLOG printf("-L/--syslog: Redirects all console output to syslog.\n"); #endif printf("--bind: Defines which address to bind to. Default is 0.0.0.0.\n"); printf("\tExample: -p 18453. Defaults to port 12345.\n"); printf("-v/--verbose: Enables verbosity\n"); printf("-h/--help: Prints this help\n\n"); printf("--debug: Enable more verbosity\n"); }
main() #endif { mount(); int i = 0; int index = 0; int retval; /* used to hold return values of file system calls */ /* do forever: 1) print a list of available commands 2) read a command 3) read arguments for the command 4) perform the requested operation 5) display the results of the operation */ while (1) { p1 = -1; p2 = -2; p3 = -1; index = 0; while(index < MAX_INPUT_LENGTH+1) { command_buffer[index] = NULL; index++; } index = 0; while(index < MAX_IO_LENGTH + 1) { io_buffer[index] = NULL; index++; } index = 0; while(index < MAX_INPUT_LENGTH) { data_buffer_1[index] = NULL; index++; } /* print a list of available commands */ printf("\n"); printf("o: open a file\n"); printf("r: read from a file\n"); printf("w: write to a file\n"); printf("R: read from a directory\n"); printf("c: close a file\n"); printf("m: create (make) a new file\n"); printf("d: delete a file\n"); printf("s: get the size of a file\n"); printf("t: get the type of a file\n"); printf("i: initialize the file system\n"); printf("q: quit - exit this program\n"); /* read in the next command */ printf("\nCommand? "); if (gets(command_buffer) == NULL ) break; /* determine which command was requested */ switch (command_buffer[0]) { case 'o': /* Open a file */ printf("Enter full path name of file to open: "); scanf(INPUT_BUF_FORMAT, data_buffer_1); retval = sfs_open(data_buffer_1); if (retval >= 0) { printf("Open succeeded. File Descriptor number is %d\n", retval); } else { printf("Error. Return value was %d\n", retval); } break; case 'r': /* Read from a file */ printf("Enter file descriptor number: "); scanf("%d", &p1); printf("Enter read start location: "); scanf("%d", &p2); printf("Enter number of bytes to read: "); scanf("%d", &p3); retval = sfs_read(p1, p2, p3, io_buffer); if (retval > 0) { printf("Read succeeded.\n"); printf( "The following data was read (only printable ASCII will display)\n"); for (i = 0; i < p3; i++) { putchar(io_buffer[i]); } printf("\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 'w': /* Write to a file */ printf("Enter file descriptor number: "); scanf("%d", &p1); printf("Enter write start location: "); scanf("%d", &p2); printf("Enter number of bytes to write: "); scanf("%d", &p3); printf( "This program allows only non-white-space, printable ASCII characters to be written to a file.\n"); printf("Enter %d characters to be written: ", p3); scanf(IO_BUF_FORMAT, io_buffer); retval = sfs_write(p1, p2, p3, io_buffer); if (retval > 0) { printf("Write succeeded.\n"); printf("Wrote %s to the disk\n", io_buffer); } else { printf("Error. Return value was %d\n", retval); } break; case 'R': /* Read from a directory */ printf("Enter file descriptor number: "); scanf("%d", &p1); retval = sfs_readdir(p1, io_buffer); if (retval > 0) { printf("sfs_readdir succeeded.\n"); printf("Directory entry is: %s\n", io_buffer); } else if (retval == 0) { printf("sfs_readdir succeeded.\n"); printf("No more entries in this directory\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 'c': /* Close a file */ printf("Enter file descriptor number: "); scanf("%d", &p1); retval = sfs_close(p1); if (retval > 0) { printf("sfs_close succeeded.\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 'm': /* Create a new file */ printf("Enter full path name of new file: "); scanf(INPUT_BUF_FORMAT, data_buffer_1); printf("Enter 0 for regular file, 1 for directory: "); scanf("%d", &p1); retval = sfs_create(data_buffer_1, p1); if (retval > 0) { printf("sfs_create succeeded.\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 'd': /* Delete a file */ printf("Enter full path name of file to delete: "); scanf(INPUT_BUF_FORMAT, data_buffer_1); retval = sfs_delete(data_buffer_1); if (retval > 0) { printf("sfs_delete succeeded.\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 's': /* Get the size of a file */ printf("Enter full path name of file: "); scanf(INPUT_BUF_FORMAT, data_buffer_1); retval = sfs_getsize(data_buffer_1); if (retval >= 0) { printf("sfs_getsize succeeded.\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 't': /* Get the type of a file */ printf("Enter full path name of file: "); scanf(INPUT_BUF_FORMAT, data_buffer_1); retval = sfs_gettype(data_buffer_1); if (retval >= 0) { printf("sfs_gettype succeeded.\n"); if (retval == 0) { printf("file type is REGULAR\n"); } else if (retval == 1) { printf("file type is DIRECTORY\n"); } else { printf("file has unknown type %d\n", retval); } } else { printf("Error. Return value was %d\n", retval); } break; case 'i': /* Initialize the file system */ printf("Enter 1 to erase disk while initializing, 0 otherwise: "); scanf("%d", &p1); retval = sfs_initialize(p1); if (retval > 0) { printf("sfs_initialize succeeded.\n"); } else { printf("Error. Return value was %d\n", retval); } break; case 'q': /* Quit this program */ break; default: printf("Unknown command: %s\n", command_buffer); break; } if (command_buffer[0] == 'q') { printf("Goodbye\n"); break; } /* cleanup the newline that remains after reading command parameter(s) */ gets(command_buffer); } }
static int handle_options(const char ***argv, int *argc, int *envchanged) { int handled = 0; while (*argc > 0) { const char *cmd = (*argv)[0]; if (cmd[0] != '-') break; /* * For legacy reasons, the "version" and "help" * commands can be written with "--" prepended * to make them look like flags. */ if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version")) break; /* * Shortcut for '-h' and '-v' options to invoke help * and version command. */ if (!strcmp(cmd, "-h")) { (*argv)[0] = "--help"; break; } if (!strcmp(cmd, "-v")) { (*argv)[0] = "--version"; break; } /* * Check remaining flags. */ if (!prefixcmp(cmd, CMD_EXEC_PATH)) { cmd += strlen(CMD_EXEC_PATH); if (*cmd == '=') set_argv_exec_path(cmd + 1); else { puts(get_argv_exec_path()); exit(0); } } else if (!strcmp(cmd, "--html-path")) { puts(system_path(PERF_HTML_PATH)); exit(0); } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) { use_pager = 1; } else if (!strcmp(cmd, "--no-pager")) { use_pager = 0; if (envchanged) *envchanged = 1; } else if (!strcmp(cmd, "--perf-dir")) { if (*argc < 2) { fprintf(stderr, "No directory given for --perf-dir.\n"); usage(perf_usage_string); } setenv(PERF_DIR_ENVIRONMENT, (*argv)[1], 1); if (envchanged) *envchanged = 1; (*argv)++; (*argc)--; handled++; } else if (!prefixcmp(cmd, CMD_PERF_DIR)) { setenv(PERF_DIR_ENVIRONMENT, cmd + strlen(CMD_PERF_DIR), 1); if (envchanged) *envchanged = 1; } else if (!strcmp(cmd, "--work-tree")) { if (*argc < 2) { fprintf(stderr, "No directory given for --work-tree.\n"); usage(perf_usage_string); } setenv(PERF_WORK_TREE_ENVIRONMENT, (*argv)[1], 1); if (envchanged) *envchanged = 1; (*argv)++; (*argc)--; } else if (!prefixcmp(cmd, CMD_WORK_TREE)) { setenv(PERF_WORK_TREE_ENVIRONMENT, cmd + strlen(CMD_WORK_TREE), 1); if (envchanged) *envchanged = 1; } else if (!strcmp(cmd, "--debugfs-dir")) { if (*argc < 2) { fprintf(stderr, "No directory given for --debugfs-dir.\n"); usage(perf_usage_string); } tracing_path_set((*argv)[1]); if (envchanged) *envchanged = 1; (*argv)++; (*argc)--; } else if (!strcmp(cmd, "--buildid-dir")) { if (*argc < 2) { fprintf(stderr, "No directory given for --buildid-dir.\n"); usage(perf_usage_string); } set_buildid_dir((*argv)[1]); if (envchanged) *envchanged = 1; (*argv)++; (*argc)--; } else if (!prefixcmp(cmd, CMD_DEBUGFS_DIR)) { tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR)); fprintf(stderr, "dir: %s\n", tracing_path); if (envchanged) *envchanged = 1; } else if (!strcmp(cmd, "--list-cmds")) { unsigned int i; for (i = 0; i < ARRAY_SIZE(commands); i++) { struct cmd_struct *p = commands+i; printf("%s ", p->cmd); } putchar('\n'); exit(0); } else if (!strcmp(cmd, "--list-opts")) { unsigned int i; for (i = 0; i < ARRAY_SIZE(options)-1; i++) { struct option *p = options+i; printf("--%s ", p->long_name); } putchar('\n'); exit(0); } else if (!strcmp(cmd, "--debug")) { if (*argc < 2) { fprintf(stderr, "No variable specified for --debug.\n"); usage(perf_usage_string); } if (perf_debug_option((*argv)[1])) usage(perf_usage_string); (*argv)++; (*argc)--; } else { fprintf(stderr, "Unknown option: %s\n", cmd); usage(perf_usage_string); } (*argv)++; (*argc)--; handled++; } return handled; }
int main() { // initializing int arrSize = INITIAL_ARR_SIZE; int wordSize = INITIAL_WORD_SIZE; int isEmpty = 1; // Initial allocation char** wordArr = (char**)malloc(sizeof(char*)*arrSize); // memory allocation failures if (wordArr == NULL) { fprintf(stderr, "Allocation failure."); exit(1); } char currChar = getchar(); // empty file if (currChar == EOF) return 0; // Check stdin if (ferror (stdin)) { fprintf(stderr, "Input failure"); exit(1); } int arrPos = 0; while (currChar != EOF) { // Check if we need to reallocate the array. // If necessary, reallocate the array using realloc. if (arrPos >= arrSize) { arrSize = arrSize*2; wordArr = realloc(wordArr, sizeof(char*)*arrSize); // memory allocation failures if (wordArr == NULL) { fprintf(stderr, "Allocation failure."); exit(1); } } // If previous part succeeds, inplement the second dimension of the array. int wordPos = 0; wordArr[arrPos] = (char*)malloc(sizeof(char)*wordSize); if (wordArr[arrPos] == NULL) { fprintf(stderr, "Allocation failure."); exit(1); } while (currChar != ' ' && currChar != EOF) { if (wordPos >= wordSize) { wordSize = wordSize*2; wordArr[arrPos] = realloc(wordArr[arrPos], sizeof(char)*wordSize); // memory allocation failures if (wordArr[arrPos] == NULL) { fprintf(stderr, "Allocation failure."); exit(1); } } // implement wordArr[arrPos][wordPos] = currChar; isEmpty = 0; // check currChar = getchar(); // Check stdin if (ferror (stdin)) { fprintf(stderr, "Input failure"); exit(1); } wordPos++; } // if (currChar == ' ' || currChar == EOF) // { while (currChar == ' ' || currChar == EOF) { // If current char is sp: if (wordArr[arrPos][wordPos] != ' ' && wordPos != 0) // change { if (wordPos >= wordSize) { wordSize = wordSize + 1; wordArr[arrPos] = realloc(wordArr[arrPos], sizeof(char)*wordSize); // memory allocation failures if (wordArr[arrPos] == NULL) { fprintf(stderr, "Allocation failure."); exit(1); } } wordArr[arrPos][wordPos] = ' '; wordPos++; } // continue the loop, check if the char is also a sp. if (currChar == EOF) break; else { currChar = getchar(); // Check stdin if (ferror (stdin)) { fprintf(stderr, "Input failure"); exit(1); } } } arrPos++; } qsort(wordArr, arrPos, sizeof(char*), frocmp); // does not contain words if (isEmpty == 1) return 0; if (ferror (stdout)) { fprintf(stderr, "Output failure."); exit(1); } for (int i = 0; i < arrPos; i++) { int j = 0; while (wordArr[i][j] != ' ') { putchar(wordArr[i][j]); // check stdout if (ferror (stdout)) { fprintf(stderr, "Output failure."); exit(1); } j++; } putchar(wordArr[i][j]); // check stdout if (ferror (stdout)) { fprintf(stderr, "Output failure."); exit(1); } } for (int i = 0; i < arrPos; i++) free(wordArr[i]); free(wordArr); return 0; }
int main(int argc, char *argv[]) { u_int flags; int ch; struct utsname uts; flags = 0; while ((ch = getopt(argc, argv, "amnrsv")) != EOF) { switch(ch) { case 'a': flags |= (MFLAG | NFLAG | RFLAG | SFLAG | VFLAG); break; case 'm': flags |= MFLAG; break; case 'n': flags |= NFLAG; break; case 'r': flags |= RFLAG; break; case 's': flags |= SFLAG; break; case 'v': flags |= VFLAG; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc) usage(); if (!flags) flags |= SFLAG; uname(&uts); if (flags & SFLAG) printf("%s ", uts.sysname); if (flags & RFLAG) printf("%s ", uts.release); if (flags & VFLAG) printf("%s ", uts.version); if (flags & MFLAG) printf("%s ", uts.machine); if (flags & NFLAG) printf("%s", uts.nodename); putchar('\n'); exit(0); }
static void test_special2z (int (*mpfr_func)(mpfr_ptr, mpz_srcptr, mpfr_srcptr, mpfr_rnd_t), void (*mpz_func)(mpz_ptr, mpz_srcptr, mpz_srcptr), const char *op) { mpfr_t x1, x2; mpz_t z1, z2; int res; mpfr_inits2 (128, x1, x2, (mpfr_ptr) 0); mpz_init (z1); mpz_init(z2); mpz_fac_ui (z1, 19); /* 19!+1 fits perfectly in a 128 bits mantissa */ mpz_add_ui (z1, z1, 1); mpz_fac_ui (z2, 20); /* 20!+1 fits perfectly in a 128 bits mantissa */ mpz_add_ui (z2, z2, 1); res = mpfr_set_z(x1, z1, MPFR_RNDN); if (res) { printf("Special2z %s: set_z1 error\n", op); exit(1); } mpfr_set_z (x2, z2, MPFR_RNDN); if (res) { printf("Special2z %s: set_z2 error\n", op); exit(1); } /* (19!+1) * (20!+1) fits in a 128 bits number */ res = mpfr_func(x1, z1, x2, MPFR_RNDN); if (res) { printf("Special2z %s: wrong inexact flag.\n", op); exit(1); } mpz_func(z1, z1, z2); res = mpfr_set_z (x2, z1, MPFR_RNDN); if (res) { printf("Special2z %s: set_z2 error\n", op); exit(1); } if (mpfr_cmp(x1, x2)) { printf("Special2z %s: results differ.\nx1=", op); mpfr_dump (x1); printf ("x2="); mpfr_dump (x2); printf ("Z2="); mpz_out_str (stdout, 2, z1); putchar('\n'); exit(1); } mpz_set_ui (z1, 0); mpz_set_ui (z2, 1); mpfr_set_ui (x2, 1, MPFR_RNDN); res = mpfr_func(x1, z1, x2, MPFR_RNDN); mpz_func (z1, z1, z2); mpfr_set_z (x2, z1, MPFR_RNDN); if (mpfr_cmp(x1, x2)) { printf("Special2z %s: results differ(2).\nx1=", op); mpfr_dump (x1); printf ("x2="); mpfr_dump (x2); exit(1); } mpz_clear (z1); mpz_clear(z2); mpfr_clears (x1, x2, (mpfr_ptr) 0); }
void Out(int a) { if(a>9) Out(a/10); putchar(a%10+'0'); }
void DisplayMods( ImageHdr * Hdr, unsigned char * image ) { Module *mod = (Module *)image; word swap, type, size, imsize; printf("\nIMAGE BODY:\n"); imsize = swapword(Hdr->Size); while ((unsigned char *)mod < image + imsize) { putchar('\n'); type = swapword(mod->Type); switch(type) { case T_Program: printf("Type = Program\n"); goto bypass; case T_Module: printf("Type = Code Module\n"); bypass: size = swapword(mod->Size); printf("Size = %#lx (%ld)\n",size,size); printf("Name = \"%s\"\n",mod->Name); swap = swapword(mod->Id); printf("Slot = %#lx (%ld)\n",swap,swap); swap = swapword(mod->Version); printf("Version = %#lx (%ld)\n",swap,swap); swap = swapword(mod->MaxData); printf("MaxData = %#lx (%ld)\n",swap,swap); swap = swapword(mod->Init); printf("Init RPTR = %#lx (%ld)\n",swap,swap); if (smtopt) { /* Cheat slightly, so we can have one version */ /* of imdump even if the Module struct has no */ /* MaxCodeP field. */ swap = swapword(*(((word *)(&mod->Init)) + 1)); printf("MaxCodeP = %#lx (%ld)\n",swap,swap); } if(type == T_Module) break; swap = swapword(((Program *)mod)->Stacksize); printf("Stacksize = %#lx (%ld)\n",swap,swap); swap = swapword(((Program *)mod)->Heapsize); printf("Heapsize = %#lx (%ld)\n",swap,swap); swap = swapword(((Program *)mod)->Main); printf("Main RPTR = %#lx (%ld)\n",swap,swap); break; case T_ResRef: printf("Type = ResRef\n"); size = swapword(((ResRef *)mod)->Size); printf("Size = %#lx (%ld)\n",size,size); printf("Require = \"%s\"\n",((ResRef *)mod)->Name); swap = swapword(((ResRef *)mod)->Id); printf("Slot = %#lx (%ld)\n",swap,swap); swap = swapword(((ResRef *)mod)->Version); printf("Version = %#lx (%ld)\n",swap,swap); break; case T_Device: /* This relies on the "Module" structure and * "Device" structure identity for the most part. * (Since <device.h> has too many Helios definitions * for a HOSTed version of this program) */ printf("Type = Device\n") ; size = swapword(mod->Size); printf("Size = %#lx (%ld)\n",size,size) ; printf("Name = \"%s\"\n",mod->Name) ; swap = swapword(mod->Version); printf("Version = %#lx (%ld)\n",swap,swap) ; swap = swapword(mod->MaxData); printf("DevOpen = %#lx (%ld)\n",swap,swap) ; break ; case 0L: /* module 0 = last module */ return; default: fprintf(stderr, "WARNING: Unknown module type %#lx - skipping\n",type); size = mod->Size; /* a definite maybe */ if (size <= 0) size = 4; break; } mod = (Module *)((char *)mod + size); } fprintf(stderr, "imdump exit - no last module indication\n"); }
/** Processes a read HID report from an attached keyboard, extracting out elements via the HID parser results * as required and prints pressed characters to the serial port. Each time a key is typed, a board LED is toggled. * * \param[in] KeyboardReport Pointer to a HID report from an attached keyboard device */ void ProcessKeyboardReport(uint8_t* KeyboardReport) { /* Check each HID report item in turn, looking for keyboard scan code reports */ for (uint8_t ReportNumber = 0; ReportNumber < HIDReportInfo.TotalReportItems; ReportNumber++) { /* Create a temporary item pointer to the next report item */ HID_ReportItem_t* ReportItem = &HIDReportInfo.ReportItems[ReportNumber]; /* Check if the current report item is a keyboard scan-code */ if ((ReportItem->Attributes.Usage.Page == USAGE_PAGE_KEYBOARD) && (ReportItem->Attributes.BitSize == 8) && (ReportItem->Attributes.Logical.Maximum > 1) && (ReportItem->ItemType == HID_REPORT_ITEM_In)) { /* Retrieve the keyboard scan-code from the report data retrieved from the device */ bool FoundData = USB_GetHIDReportItemInfo(KeyboardReport, ReportItem); /* For multi-report devices - if the requested data was not in the issued report, continue */ if (!(FoundData)) continue; /* Key code is an unsigned char in length, cast to the appropriate type */ uint8_t KeyCode = (uint8_t)ReportItem->Value; /* If scan-code is non-zero, a key is being pressed */ if (KeyCode) { /* Toggle status LED to indicate keypress */ LEDs_ToggleLEDs(LEDS_LED2); char PressedKey = 0; /* Retrieve pressed key character if alphanumeric */ if ((KeyCode >= HID_KEYBOARD_SC_A) && (KeyCode <= HID_KEYBOARD_SC_Z)) { PressedKey = (KeyCode - HID_KEYBOARD_SC_A) + 'A'; } else if ((KeyCode >= HID_KEYBOARD_SC_1_AND_EXCLAMATION) & (KeyCode < HID_KEYBOARD_SC_0_AND_CLOSING_PARENTHESIS)) { PressedKey = (KeyCode - HID_KEYBOARD_SC_1_AND_EXCLAMATION) + '1'; } else if (KeyCode == HID_KEYBOARD_SC_0_AND_CLOSING_PARENTHESIS) { PressedKey = '0'; } else if (KeyCode == HID_KEYBOARD_SC_SPACE) { PressedKey = ' '; } else if (KeyCode == HID_KEYBOARD_SC_ENTER) { PressedKey = '\n'; } /* Print the pressed key character out through the serial port if valid */ if (PressedKey) putchar(PressedKey); } /* Once a scan-code is found, stop scanning through the report items */ break; } } }
int main(int argc, char *argv[]) { /* program vars */ byte *m; /* Brain'sFuck Memory */ byte *p; /* Brain'sFuck Memory pointer */ u__int i=0;//, c, times = 1; byte *stack[STACK_LEVELS]; u__int stack_l=0; /* BF vars */ byte *mem; byte *pos; signal(SIGTERM, quitHandler); /* if(argc == 3){ if(argv[1][0] == '-'){ if(argv[1][1] == 'e') ext = 1; else{ printf("invalid argument %s\n", argv[1]); exit(1); } } else{ printf("try: %s -e file\n", argv[0]); exit(1); } }*/ if(argc == 2){ // <= 3 //if(ext == 1) m = loadfile(argv[2]); /*else*/ m = loadfile(argv[1]); } else{ printf("try: %s [-e] file\n", argv[0]); exit(EXIT_FAILURE); } p = m; // program pointer point to program memory start mem = alloc_mem(MEM_SIZE); pos = mem; //start = clock(); while(*p){ /* if(ext == 1) if(*p >= '0' && *p <= '9'){ if(!(*(p+1) >= '0' && *(p+1) <= '9')){ times = *p - '0'; p++; } } else times = 1; */ //for(c=0; c < times; c++){ switch(*p){ case '+': (*pos)++; break; case '-': (*pos)--; break; case '<': pos--; break; case '>': pos++; break; case '[': i=0; if(!*pos) while(*++p != ']' || i) switch(*p){ case '[': i++; break; case ']': i--; break; } else{ stack[++stack_l]=p; } break; case ']': if(stack_l > 0){ p = stack[stack_l]-1; stack_l--; } else{ printf("Syntax error missed ]\n"); exit(1); } break; case '.': putchar(*pos); break; case ',': *pos = getchar(); break; } //} p++; //times = 1; } //end = clock(); //printf("\nThe program takes %2.2f seconds\n", ((float)end - start) / CLK_TCK); return(0); }
int main(int argc, const char *argv[]) { char word[128]; const char *filename; queue *que; node *res, **results; /* load dictionary */ if (argc < 2) filename = "Quick+Chinese-Japanese+Dictionary.ld2.output"; else filename = argv[1]; que = load_dict(filename); /* run */ while (1) { /* input */ printf("%s", "Please input a word!\n^_^ : "); fgets(word, sizeof(word), stdin); /* remove '\n' */ if (word[strlen(word)-1] == '\n') word[strlen(word)-1] = '\0'; /* empty */ if (!strlen(word)) { putchar('\n'); continue; } /* exit */ if (strchr(word, '$')) { puts("~_~"); break; } /* search */ res = search(que, word); if (res) { search_out(res); continue; } /* similar search */ results = similar_search(que, word, results); if (*results) { printf("%s", "I can't find it. " "Show similar? (y/n): "); if (confirm()) similar_search_out(results); else putchar('\n'); } else { /* nothing */ puts("-_- : Sorry, no results!\n"); } free(results); } /* unload dictionary */ unload_dict(que); return 0; }
static void analyze_string(const char *name, const char *cap, TERMTYPE *tp) { char buf2[MAX_TERMINFO_LENGTH]; const char *sp; const assoc *ap; int tp_lines = tp->Numbers[2]; if (cap == ABSENT_STRING || cap == CANCELLED_STRING) return; (void) printf("%s: ", name); for (sp = cap; *sp; sp++) { int i; int csi; size_t len = 0; size_t next; const char *expansion = 0; char buf3[MAX_TERMINFO_LENGTH]; /* first, check other capabilities in this entry */ for (i = 0; i < STRCOUNT; i++) { char *cp = tp->Strings[i]; /* don't use soft-key capabilities */ if (strnames[i][0] == 'k' && strnames[i][0] == 'f') continue; if (cp != ABSENT_STRING && cp != CANCELLED_STRING && cp[0] && cp != cap) { len = strlen(cp); (void) strncpy(buf2, sp, len); buf2[len] = '\0'; if (_nc_capcmp(cp, buf2)) continue; #define ISRS(s) (!strncmp((s), "is", 2) || !strncmp((s), "rs", 2)) /* * Theoretically we just passed the test for translation * (equality once the padding is stripped). However, there * are a few more hoops that need to be jumped so that * identical pairs of initialization and reset strings * don't just refer to each other. */ if (ISRS(name) || ISRS(strnames[i])) if (cap < cp) continue; #undef ISRS expansion = strnames[i]; break; } } /* now check the standard capabilities */ if (!expansion) { csi = skip_csi(sp); for (ap = std_caps; ap->from; ap++) { size_t adj = (size_t) (csi ? 2 : 0); len = strlen(ap->from); if (csi && skip_csi(ap->from) != csi) continue; if (len > adj && strncmp(ap->from + adj, sp + csi, len - adj) == 0) { expansion = ap->to; len -= adj; len += (size_t) csi; break; } } } /* now check for standard-mode sequences */ if (!expansion && (csi = skip_csi(sp)) != 0 && (len = strspn(sp + csi, "0123456789;")) && (len < sizeof(buf3)) && (next = (size_t) csi + len) && ((sp[next] == 'h') || (sp[next] == 'l'))) { (void) strcpy(buf2, (sp[next] == 'h') ? "ECMA+" : "ECMA-"); (void) strncpy(buf3, sp + csi, len); buf3[len] = '\0'; len += (size_t) csi + 1; expansion = lookup_params(std_modes, buf2, buf3); } /* now check for private-mode sequences */ if (!expansion && (csi = skip_csi(sp)) != 0 && sp[csi] == '?' && (len = strspn(sp + csi + 1, "0123456789;")) && (len < sizeof(buf3)) && (next = (size_t) csi + 1 + len) && ((sp[next] == 'h') || (sp[next] == 'l'))) { (void) strcpy(buf2, (sp[next] == 'h') ? "DEC+" : "DEC-"); (void) strncpy(buf3, sp + csi + 1, len); buf3[len] = '\0'; len += (size_t) csi + 2; expansion = lookup_params(private_modes, buf2, buf3); } /* now check for ECMA highlight sequences */ if (!expansion && (csi = skip_csi(sp)) != 0 && (len = strspn(sp + csi, "0123456789;")) != 0 && (len < sizeof(buf3)) && (next = (size_t) csi + len) && sp[next] == 'm') { (void) strcpy(buf2, "SGR:"); (void) strncpy(buf3, sp + csi, len); buf3[len] = '\0'; len += (size_t) csi + 1; expansion = lookup_params(ecma_highlights, buf2, buf3); } if (!expansion && (csi = skip_csi(sp)) != 0 && sp[csi] == 'm') { len = (size_t) csi + 1; (void) strcpy(buf2, "SGR:"); strcat(buf2, ecma_highlights[0].to); expansion = buf2; } /* now check for scroll region reset */ if (!expansion && (csi = skip_csi(sp)) != 0) { if (sp[csi] == 'r') { expansion = "RSR"; len = 1; } else { (void) sprintf(buf2, "1;%dr", tp_lines); len = strlen(buf2); if (strncmp(buf2, sp + csi, len) == 0) expansion = "RSR"; } len += (size_t) csi; } /* now check for home-down */ if (!expansion && (csi = skip_csi(sp)) != 0) { (void) sprintf(buf2, "%d;1H", tp_lines); len = strlen(buf2); if (strncmp(buf2, sp + csi, len) == 0) { expansion = "LL"; } else { (void) sprintf(buf2, "%dH", tp_lines); len = strlen(buf2); if (strncmp(buf2, sp + csi, len) == 0) { expansion = "LL"; } } len += (size_t) csi; } /* now look at the expansion we got, if any */ if (expansion) { printf("{%s}", expansion); sp += len - 1; } else { /* couldn't match anything */ buf2[0] = *sp; buf2[1] = '\0'; fputs(TIC_EXPAND(buf2), stdout); } } putchar('\n'); }
void AfProgressDlg::StepIt(int nIncrement) { if (TestMigrateData::g_fVerbose) putchar('.'); }
int main(int argc, char* argv[]) { int i = 0; msg_type messages[4]; unsigned num_msg = sizeof(messages) / sizeof(messages[0]); struct timespec timeread; struct timespec timedelay; int fd = -1; char* port = "/dev/can1"; char line[1024]; char* read = NULL; int linenum = 0; uint8_t extended = 0; int nmax = 0; int opt = 0; int verbose = 0; // parse the command-line args while ((opt = getopt(argc, argv, "e:n:p:v:z")) != -1) { printf ("opt = %d\n", opt); switch (opt) { case 'e': extended = 1; break; case 'n': nmax = atoi(optarg); break; case 'p': port = strdup(optarg); break; case 'v': verbose = 1; break; } } memset(messages, 0, sizeof(messages)); for (i = 0; i < num_msg; ++i) { messages[i].frequency = i * 10 + 10; // 10Hz, 20Hz, 30Hz, etc... messages[i].period = 1000 / messages[i].frequency; } // read 10 lines of messages from stdin read = fgets(line, sizeof(line), stdin); while ((int)read != EOF && read != NULL) { char* token = strtok(line, " \t"); int num_msg_incoming = atoi(token); int id; // check number of messages matches the number we can store if (num_msg_incoming != num_msg) { fprintf(stderr, "number of messages don't match: %d, %d\n", num_msg_incoming, num_msg); continue; } for (i = 0; i < num_msg_incoming; i++) { msg_descriptor_t* p = NULL; uint64_t msg_raw = 0; token = strtok(NULL, " \t"); id = atoi(token); p = &msg_descriptors[id / 100 - 1]; if (messages[i].id != p->identifier) { if (messages[i].id == 0) messages[i].id = p->identifier; else { fprintf(stderr, "identifers don't match."); continue; } } msg_raw = parse_msg_input(p, NULL, NULL); messages[i].data[linenum] = msg_raw; if (verbose) { printf ("msg parsed: "); print_data(msg_raw); putchar('\n'); } } linenum++; read = fgets(line, sizeof(line), stdin); } puts("input data correctly parsed."); // initialize the timedelay structure timedelay.tv_sec = 0; timedelay.tv_nsec = 10000000; /* 10 millsecs */ // open can port fd = can_open(port, O_WRONLY); if (fd == -1) { fprintf (stderr, "error opening %s\n", port); exit(1); } printf ("can port opened. fd = %d\n", fd); // keep on sending data until someone decides to press ctrl+C for (;;) { unsigned now_ms; clock_gettime(CLOCK_REALTIME, &timeread); now_ms = timeread.tv_sec * 1000 + timeread.tv_nsec / 1000000; for (i = 0; i < num_msg; ++i) { // see how long it has been since that message was last sent unsigned long diff = now_ms - messages[i].lastsent; // if longer than period, send again if (diff >= messages[i].period) { int rand_msg = rand() % 10; can_write(fd, messages[i].id, 0, &messages[i].data[rand_msg], // pick random 8); if (verbose) { printf ("msg sent: i=%d, id=%d, msg_index=%d, data= ", i, messages[i].id, rand_msg); print_data(messages[i].data[rand_msg]); putchar('\n'); } messages[i].lastsent = now_ms; } } // sleep for 10 ms to avoid using all the cpu // nanosleep(&timedelay, NULL); } return 0; }