long double t20(char **x) { return strtold("123.4", x); }
static void read_floating(struct tok_floating *out, const struct scan_number *sn, tok_message_queue *mq) { /* Assertions about a float's struct scan_number: prefix is empty or [0B 0b 0X 0x] (note: no octal prefix 0) sn->digits not empty, ever exponent may or may not exist If exponent exists, it is valid and formatted as: ( [E P e p] ['+' '-']*0..1 [0-9]* ) An exponent starts with E if this is decimal, P if it is hex/binary suffix is [0-9 A-Z a-z '.']* dots_found can be anything */ const char *tokstart = sn->prefix; const char *s = sn->prefix, *e = sn->suffix; char borrow = *sn->end; //long double strtold(const char *nptr, char **endptr); out->v = 0.0; out->suffix = TOK_NOSUFFIX; if (sn->prefix < sn->digits) { if (sn->prefix[1]=='B' || sn->prefix[1]=='b') { tok_msg_error(binary_float, tokstart, "Binary floating point constants not allowed"); return; } if (sn->exponent >= sn->suffix) { tok_msg_error(hex_float_no_exponent, tokstart, "Hex floating point constant missing exponent"); return; } } /* Stick a null terminator at the end of the input so strtold * won't read beyond the given input. * * This is thread-safe because the input is from * token_list.txt, which was generated in the * tokenize function which is still running. */ *(char*)sn->end = 0; errno = 0; out->v = strtold(s, (char**)&s); //don't forget to set it back *(char*)sn->end = borrow; if (errno) { //for some reason, strtold may errno to EDOM to indicate underrun //open test/run.c and search "floating_out_of_range" for more details if (errno == ERANGE || errno == EDOM) { tok_msg_error(floating_out_of_range, tokstart, "Floating point constant out of range"); } else { tok_msg_bug(strtold_unknown, tokstart, "Unknown error returned by strtold"); } } if (s != e) { tok_msg_error(floating_invalid_digits, tokstart, "Floating point constant contains invalid digits"); } out->suffix = read_number_suffix(sn->suffix, sn->end, TOK_FLOATING, mq); }
int main(int argc, char **argv) { int opt; char *ptr; int linenr, posnr, diff; char line1[MAXLINELEN], line2[MAXLINELEN]; char *ptr1, *ptr2; int pos1, pos2; int read1, read2, n1, n2; flt f1, f2; flt absdiff, reldiff; progname = argv[0]; /* Parse command-line options */ abs_prec = default_abs_prec; rel_prec = default_rel_prec; show_help = show_version = 0; opterr = 0; while ( (opt = getopt_long(argc,argv,"a:r:",long_opts,(int *) 0))!=-1 ) { switch ( opt ) { case 0: /* long-only option */ break; case 'a': /* absolute precision */ abs_prec = strtold(optarg,&ptr); if ( *ptr!=0 || ptr==(char *)&optarg ) error(errno,"incorrect absolute precision specified"); break; case 'r': /* relative precision */ rel_prec = strtold(optarg,&ptr); if ( *ptr!=0 || ptr==(char *)&optarg ) error(errno,"incorrect relative precision specified"); break; case ':': /* getopt error */ case '?': error(0,"unknown option or missing argument `%c'",optopt); break; default: error(0,"getopt returned character code `%c' ??",(char)opt); } } if ( show_help ) usage(); if ( show_version ) version(); if ( argc<optind+3 ) error(0,"not enough arguments given"); file1name = argv[optind+1]; file2name = argv[optind+2]; if ( strcmp(file1name,"-")==0 && strcmp(file2name,"-")==0 ) { error(0,"both files specified as standard input"); } if ( strcmp(file1name,"-")==0 ) { file1 = stdin; } else { if ( (file1 = fopen(file1name,"r"))==NULL ) error(errno,"cannot open '%s'",file1name); } if ( strcmp(file2name,"-")==0 ) { file2 = stdin; } else { if ( (file2 = fopen(file2name,"r"))==NULL ) error(errno,"cannot open '%s'",file2name); } linenr = 0; diff = 0; while ( 1 ) { linenr++; ptr1 = fgets(line1,MAXLINELEN,file1); ptr2 = fgets(line2,MAXLINELEN,file2); if ( ptr1==NULL && ptr2==NULL ) break; if ( ptr1==NULL && ptr2!=NULL ) { printf("line %3d: file 1 ended before 2.\n",linenr); diff++; break; } if ( ptr1!=NULL && ptr2==NULL ) { printf("line %3d: file 2 ended before 1.\n",linenr); diff++; break; } pos1 = pos2 = 0; posnr = 0; while ( 1 ) { posnr++; read1 = sscanf(&line1[pos1],"%Lf",&f1); read2 = sscanf(&line2[pos2],"%Lf",&f2); sscanf(&line1[pos1],"%*f%n",&n1); sscanf(&line2[pos2],"%*f%n",&n2); pos1 += n1; pos2 += n2; if ( read1==EOF && read2==EOF ) break; if ( read1!=1 && read2==1 ) { printf("line %3d: file 1 misses %d-th float.\n",linenr,posnr); diff++; break; } if ( read1==1 && read2!=1 ) { printf("line %3d: file 1 has excess %d-th float.\n",linenr,posnr); diff++; break; } if ( read1==0 ) { printf("line %3d: file 1, %d-th entry cannot be parsed as float.\n", linenr,posnr); diff++; break; } if ( read2==0 ) { printf("line %3d: file 2, %d-th entry cannot be parsed as float.\n", linenr,posnr); diff++; break; } if ( !(read1==1 && read2==1) ) { error(0,"error reading float on line %d",linenr); } if ( ! equal(f1,f2) ) { diff++; printf("line %3d: %d-th float differs: %8LG != %-8LG", linenr,posnr,f1,f2); if ( isfinite(f1) && isfinite(f2) ) { absdiff = fabsl(f1-f2); reldiff = fabsl((f1-f2)/f2); if ( absdiff>abs_prec ) printf(" absdiff = %9.5LE",absdiff); if ( reldiff>rel_prec ) printf(" reldiff = %9.5LE",reldiff); } printf("\n"); } } } fclose(file1); fclose(file2); if ( diff > 0 ) printf("Found %d differences in %d lines\n",diff,linenr-1); return 0; }
struct arg_data handleArgs(int argc, char **argv) { struct option long_options[] = { {"logfile", required_argument, 0, 'l'}, {"execute", required_argument, 0, 'e'}, {"multiplex", required_argument, 0, 'm'}, {"ftok", required_argument, 0, 'f'}, {"ipc", required_argument, 0, 'i'} }; int c, exitFlag = 0, is_there_execute = 0; struct arg_data argData; argData.multiplex = 1; int logfile_fd = 2; argData.ipcType = 0; while (!exitFlag) { c = getopt_long(argc, argv, "l:e:m:f:i:", long_options, 0); switch (c) { case 'l': logfile_fd = open(optarg, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (logfile_fd < 0) { char *buffer = strerror(errno); write(2, buffer, strlen(buffer)); logfile_fd = 2; } argData.logfile_fd = logfile_fd; break; case 'e': argData.executeFile = optarg; is_there_execute = 1; break; case 'm': argData.multiplex = strtold(optarg, 0); break; case 'f': argData.ftokPath = optarg; break; case 'i': if (strcmp(optarg, "posix") == 0) { argData.ipcType = 0; } else if (strcmp(optarg, "sysv") == 0) { argData.ipcType = 1; } else { char *buffer = "You should set IPC type\n"; write(2, buffer, strlen(buffer)); exit(1); } break; case '?': abort(); default: exitFlag = 1; break; } } if (!is_there_execute) { char *buffer = "There is nothing to execute\n"; write(2, buffer, strlen(buffer)); exit(1); } return argData; }
void SocketHelperFunctions::unmarshalArrayFromBufferAsTypeIntoExistingMemory(char *&buffer, std::pair<llvm::Type::TypeID, unsigned> typeIDAndBitwidthPointedTo, void* pointerToMemory) { int64_t numberOfElements = strtoll(buffer, &buffer, 10); buffer++; switch (typeIDAndBitwidthPointedTo.first) { case llvm::Type::FloatTyID: for (int i = 0; i != numberOfElements; i++) { ((float*)pointerToMemory)[i] = strtod(buffer, &buffer); buffer++; } break; case llvm::Type::DoubleTyID: for (int i = 0; i != numberOfElements; i++) { ((double*)pointerToMemory)[i] = strtod(buffer, &buffer); buffer++; } break; case llvm::Type::X86_FP80TyID: case llvm::Type::FP128TyID: for (int i = 0; i != numberOfElements; i++) { ((long double*)pointerToMemory)[i] = strtold(buffer, &buffer); buffer++; } break; case llvm::Type::IntegerTyID: switch(typeIDAndBitwidthPointedTo.second) { case 8: for (int i = 0; i != numberOfElements; i++) { ((int8_t*)pointerToMemory)[i] = strtol(buffer, &buffer, 16); buffer++; } break; case 16: for (int i = 0; i != numberOfElements; i++) { ((int16_t*)pointerToMemory)[i] = strtol(buffer, &buffer, 16); buffer++; } break; case 32: for (int i = 0; i != numberOfElements; i++) { ((int32_t*)pointerToMemory)[i] = strtol(buffer, &buffer, 16); buffer++; } break; case 64: for (int i = 0; i != numberOfElements; i++) { ((int64_t*)pointerToMemory)[i] = strtoll(buffer, &buffer, 16); buffer++; } break; default: for (int i = 0; i != numberOfElements; i++) { ((int*)pointerToMemory)[i] = strtol(buffer, &buffer, 16); buffer++; } } break; default: std::cerr << "LLVM TypeID " << typeIDAndBitwidthPointedTo.first << " is not supported as array element.\n"; exit(1); } buffer--; return; }
void eu0011 :: solucion(){ // ---------------------------------------------------- // tstart = (double)clock()/CLOCKS_PER_SEC; // ---------------------------------------------------- // output = 0; tem_2d_1 = new unsigned long long *[20]; for ( unsigned int i=0; i<20; i++ ){ tem_2d_1[i] = new unsigned long long [20]; } // ---------------------------------------------------- // char uu[3]; myfile_read_1.open("eu0011_data.txt"); // myfile_read_1.setf( ios::fixed ); for( unsigned int i=0; i<20; i++ ){ for( unsigned int j=0; j<20; j++ ){ myfile_read_1.get(uu, 3); tem_2d_1[i][j] = strtold(uu,0); myfile_read_1.ignore(1,' '); } } // Arriba a Abajo for( unsigned int j=0; j<20; j++ ){ for( unsigned int k=0; k<17; k++ ){ temp_1 = 1; for( unsigned int i=k; i<k+4; i++ ){ temp_1 = temp_1*tem_2d_1[i][j]; } if( output < temp_1 ){ output = temp_1; } } } // Lateral for( unsigned int i=0; i<20; i++ ){ for( unsigned int k=0; k<17; k++ ){ temp_1 = 1; for( unsigned int j=k; j<k+4; j++ ){ temp_1 = temp_1*tem_2d_1[i][j]; } if( output < temp_1 ){ output = temp_1; } } } // Diagonal for( unsigned int i=0; i<17; i++ ){ for( unsigned int j=0; j<17; j++ ){ temp_1 = 1; for( unsigned int k=0; k<4; k++ ){ temp_1 = temp_1*tem_2d_1[i+k][j+k]; } if( output < temp_1 ){ output = temp_1; } } } // Diagonal 2 for( unsigned int i=3; i<20; i++ ){ for( unsigned int j=0; j<17; j++ ){ temp_1 = 1; for( unsigned int k=0; k<4; k++ ){ temp_1 = temp_1*tem_2d_1[i-k][j+k]; } if( output < temp_1 ){ output = temp_1; } } } // ---------------------------------------------------- // tstop = (double)clock()/CLOCKS_PER_SEC; ttime= tstop-tstart; // ---------------------------------------------------- // }
long double strtold_l(const char* s, char** end_ptr, locale_t) { return strtold(s, end_ptr); }
int main (void) { char buf[300]; int cnt; int result = 0; for (cnt = 0; cnt < 200; ++cnt) { ssize_t n; float f; n = sprintf (buf, "%d", cnt); memset (buf + n, '0', cnt); sprintf (buf + n + cnt, ".000e-%d", cnt); f = strtof (buf, NULL); if (f != (float) cnt) { printf ("strtof(\"%s\") failed for cnt == %d (%g instead of %g)\n", buf, cnt, f, (float) cnt); result = 1; } else printf ("strtof() fine for cnt == %d\n", cnt); } for (cnt = 0; cnt < 200; ++cnt) { ssize_t n; double f; n = sprintf (buf, "%d", cnt); memset (buf + n, '0', cnt); sprintf (buf + n + cnt, ".000e-%d", cnt); f = strtod (buf, NULL); if (f != (double) cnt) { printf ("strtod(\"%s\") failed for cnt == %d (%g instead of %g)\n", buf, cnt, f, (double) cnt); result = 1; } else printf ("strtod() fine for cnt == %d\n", cnt); } for (cnt = 0; cnt < 200; ++cnt) { ssize_t n; long double f; n = sprintf (buf, "%d", cnt); memset (buf + n, '0', cnt); sprintf (buf + n + cnt, ".000e-%d", cnt); f = strtold (buf, NULL); if (f != (long double) cnt) { printf ("strtold(\"%s\") failed for cnt == %d (%Lg instead of %Lg)\n", buf, cnt, f, (long double) cnt); result = 1; } else printf ("strtold() fine for cnt == %d\n", cnt); } return result; }
int put_str_one(void *buf,char *cp,T_PkgType *typ,char CURDLM) { int ret; register char *cp1; cp1=typ->offset+(char *)buf; ret=0; switch(typ->type) { case CH_CLOB: *(char **)cp1=cp; if(CURDLM) strcpy_esc(cp,cp,-1,CURDLM); //有问题 typ->len=strlen(cp); ret=1; break; case CH_BYTE: byte_cpy(cp1,cp,typ->len); ret=1; break; case CH_DATE: case CH_CNUM: case CH_CHAR: *cp1=0; strcpy_esc(cp1,cp,typ->len,CURDLM); ret=1; break; case CH_FLOAT: *(float *)cp1=strtof(cp,&cp);; ret=1; break; case CH_DOUBLE: *(double *)cp1=strtod(cp,&cp);; ret=1; break; case CH_LDOUBLE: *(long double *)cp1=strtold(cp,&cp); break; case CH_JUL: case CH_CJUL: if(!*cp) *(INT4 *)cp1=TIMENULL; else if(typ->format){ *(int *)cp1=rstrfmttojul(cp, typ->format); } else { *(int *)cp1= rstrjul(cp); } ret=1; break; case CH_MINUTS: case CH_CMINUTS: if(!*cp) *(INT4 *)cp1=TIMENULL; else if(typ->format){ *(INT4 *)cp1=rstrminfmt(cp,typ->format); } else *(INT4 *)cp1=rstrmin(cp); ret=1; break; case CH_TIME: case CH_CTIME: if(!*cp) *(INT64 *)cp1=INT64NULL; else if(typ->format){ *(INT64 *)cp1=rstrsecfmt(cp,typ->format); } else *(INT64 *)cp1=rstrsecfmt(cp,"YYYYMMDDHH24MISS"); ret=1; break; case CH_USEC: if(!*cp) *(INT64 *)cp1=INT64NULL; else if(typ->format){ *(INT64 *)cp1=rstrusecfmt(cp,typ->format); } else *(INT64 *)cp1=rstrusecfmt(cp,"YYYYMMDDHH24MISS.FF6"); ret=1; break; case CH_TINY: { int tmp; if(!*cp) { *cp1=TINYNULL; break; } tmp=atoi(cp); *cp1=(char)tmp; break; } case CH_SHORT: *(short *)cp1=SHORTNULL; ret=sscanf(cp,"%hd",(short *)cp1); ret=1; break; case CH_INT: if(!*cp) { *(int *)cp1=INTNULL; break; } *(int *)cp1=atoi(cp); break; case CH_LONG: if(!*cp) { *(long *)cp1=LONGNULL; break; } *(long *)cp1=strtol(cp,&cp,10); break; case CH_INT64: if(!*cp) { *(INT64 *)cp1=INT64NULL; break; } *(INT64 *)cp1=strtoll(cp,&cp,10); break; default: ret=0; break; } return ret; }
long double nanl(const char *tagp) { char buf[256]; sprintf(buf,"NAN(%.250s)",tagp); return strtold(buf,NULL); }
int main(int argc, char *argv[]) { char ch, *str, *strStart; int i; double number; struct String input = {NULL, 0, 0, 5}; /* Kick off scope */ struct Scope *currentScope = NULL; addScope(currentScope, ¤tScope); /* Read input from... */ if (argc == 1) { /* stdin */ while ((ch = getchar()) != '\n' && ch != EOF) { stringAddChar(&input, ch); } } else { /* args */ for (i = 1; i < argc; i++) { stringAddStr(&input, argv[i]); stringAddChar(&input, ' '); } } /* Tokenise */ str = input.str; while (*str != '\0') { strStart = str; if (isspace(*str)) { /* Space */ str++; } else if (*str == '(') { addScope(currentScope, ¤tScope); str++; } else if (*str == ')') { insertToken(currentScope, NUM, '\0', evaluateScope(currentScope, ¤tScope)); str++; } else if ((number = strtold(str, &str)) == 0.0L && (number = strtoconst(str, &str)) == 0.0L) { /* NaN */ insertToken(currentScope, OP, normalise(*str), 0); str++; } else { /* Number */ if ((*strStart == '+' || *strStart == '-') && currentScope->last != NULL && strcmp(currentScope->last->type, OP)) { //Assume this was supposed to be an operation insertToken(currentScope, OP, *strStart, 0); } insertToken(currentScope, NUM, '\0', number); } } /* * TODO: Increase precision * TODO: Allow precision to be specified */ printf("%.15g\n", evaluateScope(currentScope, ¤tScope)); free(input.str); return 0; }
int parse_args (int argc, char *argv[], table_t *tab) { unsigned char haveflags = 0; /* 1 1 1 1 1 1 1 1 | | | | | \- method | | | | \--- out fname | | | \----- in fname | | \------- cols to skip | \--------- rows to skip \----------- Field sep */ char c = '\0'; while((c = getopt(argc, argv, "mCM:r:c:o:i:s:h")) >= 0) { switch (c) { case 'm': haveflags |= 1; tab->row_fn = &dm_manhattan; tab->mode = D64; break; case 'M': haveflags |= 1; tab->row_fn = &dm_manhattan_binary; tab->mode = D64; binary_cutoff.d = strtold(optarg, NULL); break; case 'C': haveflags |= 1; tab->mode = D64; tab->row_fn = &dm_canberra; break; case 'o': haveflags |= 2; tab->outfname = strdup(optarg); break; case 'i': haveflags |= 4; tab->fname = strdup(optarg); break; case 'c': haveflags |= 8; tab->skipcol = atol(optarg); break; case 'r': haveflags |= 16; tab->skiprow = atol(optarg); break; case 's': haveflags |= 32; tab->sep = strdup(optarg); break; case 'h': print_usage(); destroy_distmat_table_t(tab); exit(EXIT_SUCCESS); } } if (tab->sep == NULL) { tab->sep = strdup("\t"); } /* Setup input fp */ if ((!(haveflags & 4)) || tab->fname == NULL || \ strncmp(tab->fname, "-", 1) == 0) { tab->fp = fdopen(fileno(stdin), "r"); tab->fname = strdup("stdin"); haveflags |= 4; } else { tab->fp = fopen(tab->fname, "r"); } if (tab->fp == NULL) { fprintf(stderr, "Could not open file '%s'\n%s\n", tab->fname, strerror(errno)); return 0; } /* Setup output fp */ if ((!(haveflags & 2)) || tab->outfname == NULL || \ strncmp(tab->outfname, "-", 1) == 0) { tab->outfp = fdopen(fileno(stdout), "w"); tab->outfname = strdup("stdout"); haveflags |= 2; } else { tab->outfp = fopen(tab->outfname, "w"); } if (tab->outfp == NULL) { fprintf(stderr, "Could not open file '%s'\n%s\n", tab->outfname, strerror(errno)); return 0; } if ((haveflags & 7) != 7) { fprintf(stderr, "[parse_args] Required arguments missing\n"); return 0; } return 1; /* Successful */ }
unsigned int parse_memory_size(const char *sizeName, /* "initial heap" or "maximum heap" or "initial stack" or "maximum stack" */ const char *sizeFlag, // "-Xms" or "-Xmx" or // "-Xss" or "-Xsg" or "-Xsx" const char *defaultFactor, // We now always default to bytes ("") unsigned roundTo, // Round to PAGE_SIZE_BYTES or to 4. const char *token /* e.g., "-Xms200M" or "-Xms200" */, const char *subtoken /* e.g., "200M" or "200" */, bool *fastExit) { errno = 0; long double userNum; char *endp; /* Should be const char *, but if we do that, then the C++ compiler complains about the prototype for strtold() or strtod(). This is probably a bug in the specification of the prototype. */ #ifdef HAVE_CXX_STRTOLD /* This gets around some nastiness in AIX 5.1, where <stdlib.h> only prototypes strtold() if we're using the 96 or 128 bit "long double" type. Which is an option to the IBM Visual Age C compiler, but apparently not (yet) available for GCC. */ userNum = strtold(subtoken, &endp); #else userNum = strtod(subtoken, &endp); #endif if (endp == subtoken) { fprintf(SysTraceFile, "%s: \"%s\": -X%s must be followed" " by a number.\n", Me, token, sizeFlag); *fastExit = true; } // First, set the factor appropriately, and make sure there aren't extra // characters at the end of the line. const char *factorStr = defaultFactor; long double factor = 0.0; // 0.0 is a sentinel meaning Unset if (*endp == '\0') { /* no suffix. Along with the Sun JVM, we now assume Bytes by default. (This is a change from previous Jikes RVM behaviour.) */ factor = 1.0; // Don't use C or c, since they are hexadecimal digits. // } else if (strequal(endp, "c")) { // /* The "dd" Unix utility has used "c" for "characters" to mean what we // mean by bytes, so we go ahead and make "c" legal syntax. This is // handled specially, since we don't want to treat "cib" or "cB" as // legal -- that would just be sick. */ // factor = 1.0; // We don't use "p" for "pages" so that we can avoid conflicting with // Petabytes one day. } else if (strequal(endp, "pages") // || strequal(endp, "p") ) { factor = BYTES_IN_PAGE; } else if ( /* Handle constructs like "M" and "K" */ endp[1] == '\0' /* Handle constructs like "MiB" or "MB". We stand with common practice in the programming community and against ISO, by having KB of memory be units of 1024, not units of 1000. */ || strequal(endp + 2, "iB") || strequal(endp + 2, "ib") || strequal(endp + 2, "B") || strequal(endp + 2, "b") ) { factorStr = endp; } else { fprintf(SysTraceFile, "%s: \"%s\": I don't recognize \"%s\" as a" " unit of memory size\n", Me, token, endp); *fastExit = true; } if (! *fastExit && factor == 0.0) { char e = *factorStr; /* At this time, with our using a 32-bit quantity to indicate memory * size, we can't use T and above, and we are unlikely to use G. But * it doesn't hurt to have the code in here, since a double is * guaranteed to be able to represent quantities of the magnitude * 2^40, and this only wastes a couple of instructions, once during * the program run. When we go up to 64 bits, we'll be glad. I * think. --steve augart */ // Don't use E alone for now -- E is a hex digit. // if (e == 'e' || e == 'E') // Exbibytes // factor = 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0; // else if (e == 'p' || e == 'P') // Pebibytes factor = 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0; else if (e == 't' || e == 'T') // Tebibytes /* We'll always recognize T and above, but we don't show those sizes in the help message unless we're on a 64-bit platform, since they're not useful on a 32-bit platform. */ factor = 1024.0 * 1024.0 * 1024.0 * 1024.0; // Tebibytes else if (e == 'g' || e == 'G') factor = 1024.0 * 1024.0 * 1024.0; // Gibibytes else if (e == 'm' || e == 'M') factor = 1024.0 * 1024.0; // Mebibytes else if (e == 'k' || e == 'K') factor = 1024.0; // Kibibytes // We have gotten rid of the B suffix, since B is a hexadecimal digit. // else if (e == 'b' || e == 'B') // factor = 1.0; else if (e == '\0') { // Absence of a suffix means Bytes. factor = 1.0; } else { fprintf(SysTraceFile, "%s: \"%s\": I don't recognize \"%s\" as a" " unit of memory size\n", Me, token, factorStr); *fastExit = true; } } // Note: on underflow, strtod() returns 0. if (!*fastExit) { if (userNum <= 0.0) { fprintf(SysTraceFile, "%s: You may not specify a %s %s;\n", Me, userNum < 0.0 ? "negative" : "zero", sizeName); fprintf(SysTraceFile, "\tit just doesn't make any sense.\n"); *fastExit = true; } } if (!*fastExit) { if ( errno == ERANGE || userNum > ((long double) (UINT_MAX - roundTo)/factor)) { fprintf(SysTraceFile, "%s: \"%s\": out of range" " to represent internally\n", Me, subtoken); *fastExit = true; } } if (*fastExit) { fprintf(SysTraceFile, "\tPlease specify %s as follows:\n", sizeName); fprintf(SysTraceFile, "\t in bytes, using \"-X%s<positive number>\",\n", sizeFlag); fprintf(SysTraceFile, "\tor, in kilobytes (kibibytes), using \"-X%s<positive number>K\",\n", sizeFlag); fprintf(SysTraceFile, "\tor, in virtual memory pages of %u bytes, using\n" "\t\t\"-X%s<positive number>pages\",\n", BYTES_IN_PAGE, sizeFlag); fprintf(SysTraceFile, "\tor, in megabytes (mebibytes), using \"-X%s<positive number>M\",\n", sizeFlag); fprintf(SysTraceFile, "\tor, in gigabytes (gibibytes), using \"-X%s<positive number>G\"", sizeFlag); // #ifdef RVM_FOR_64_ADDR fprintf(SysTraceFile, ",\n"); fprintf(SysTraceFile, "\tor, in terabytes (tebibytes), using \"-X%s<positive number>T\"", sizeFlag); fprintf(SysTraceFile, ",\n"); fprintf(SysTraceFile, "\tor, in petabytes (pebibytes), using \"-X%s<positive number>P\"", sizeFlag); // fprintf(SysTraceFile, ",\n"); // fprintf(SysTraceFile, // "\tor, in exabytes (exbibytes), using \"-X%s<positive number>E\"", // sizeFlag); // #endif // RVM_FOR_64_ADDR fprintf(SysTraceFile, ".\n"); fprintf(SysTraceFile, " <positive number> can be a floating point value or a hex value like 0x10cafe0.\n"); if (roundTo != 1) { fprintf(SysTraceFile, " The # of bytes will be rounded up to a multiple of"); if (roundTo == BYTES_IN_PAGE) fprintf(SysTraceFile, "\n the virtual memory page size: "); fprintf(SysTraceFile, "%u\n", roundTo); } return 0U; // Distinguished value meaning trouble. } long double tot_d = userNum * factor; assert(tot_d <= (UINT_MAX - roundTo)); assert(tot_d >= 1); unsigned tot = (unsigned) tot_d; if (tot % roundTo) { unsigned newTot = tot + roundTo - (tot % roundTo); fprintf(SysTraceFile, "%s: Rounding up %s size from %u bytes to %u,\n" "\tthe next multiple of %u bytes%s\n", Me, sizeName, tot, newTot, roundTo, roundTo == BYTES_IN_PAGE ? ", the virtual memory page size" : ""); tot = newTot; } return tot; }
void create_bodies() { FILE* inputdataf = fopen("inputData", "r"); int i = 0; char line[100]; char* token; char* end; double d = 0.0; for (i = 0; i < nbodies; i++) { // printf("i = %d \n", i); bodies[i] = malloc(sizeof(node_t)); leaf_t* leaf = malloc(sizeof(leaf_t)); fgets(line, 100, inputdataf); // printf("%s\n", line); token = strtok(line, " "); d = strtold(token, &end); leaf->mass = d; // printf("%lf\n",d); token = strtok(NULL, " "); d = strtold(token, &end); leaf->pos[0] = d; // printf("%lf\n",d); token = strtok(NULL, " "); d = strtold(token, &end); leaf->pos[1] = d; // printf("%lf\n",d); token = strtok(NULL, " "); d = strtold(token, &end); leaf->pos[2] = d; // printf("%lf\n",d); token = strtok(NULL, " "); d = strtold(token, &end); leaf->vel[0] = d; // printf("%lf\n",d); token = strtok(NULL, " "); d = strtold(token, &end); leaf->vel[1] = d; // printf("%lf\n",d); token = strtok(NULL, " "); d = strtold(token, &end); leaf->vel[2] = d; // printf("%lf\n",d); leaf->acc[0] = 0.0; leaf->acc[1] = 0.0; leaf->acc[2] = 0.0; leafs[i] = *leaf; bodies[i]->type = 0; bodies[i]->cell.leaf = &leafs[i]; bodies[i]->mass = &bodies[i]->cell.leaf->mass; bodies[i]->pos = bodies[i]->cell.leaf->pos; free(leaf); } fclose(inputdataf); }
float strtof(const char *nptr, char **endptr) { return (float) strtold(nptr, endptr); }
long double strtold_l (const char *nptr, char **endptr, locale_t loc) { return strtold(nptr, endptr); }
static long double clay_strtold(char *ptr, char **end) { // XXX parse hex long doubles return strtold(ptr, end); }
meterd_rv meterd_parse_p1_telegram(telegram_ll* telegram, const char* gas_id, smart_counter** counters) { assert(telegram != NULL); assert(counters != NULL); const char* re_simple = "[0-9]-[0-9]:([0-9]+\\.[0-9]+\\.[0-9]+)[(](.*)[)]"; const char* re_gas = "[(](.*)[)]"; const char* re_counterval = "([0-9.]*)[*]([A-Za-z0-9]*)"; regmatch_t simple_m[3]; regmatch_t gas_m[2]; regmatch_t counterval_m[3]; int next_is_gas = 0; regex_t re_simple_c = { 0 }; regex_t re_gas_c = { 0 }; regex_t re_counterval_c = { 0 }; int rv = 0; telegram_ll* telegram_it = NULL; /* Set up regular expressions */ if ((rv = regcomp(&re_simple_c, re_simple, REG_EXTENDED)) != 0) { DEBUG_MSG("Regex failed to compile: %d\n", rv); return MRV_GENERAL_ERROR; } if ((rv = regcomp(&re_gas_c, re_gas, REG_EXTENDED)) != 0) { DEBUG_MSG("Regex failed to compile: %d\n", rv); regfree(&re_simple_c); return MRV_GENERAL_ERROR; } if ((rv = regcomp(&re_counterval_c, re_counterval, REG_EXTENDED)) != 0) { DEBUG_MSG("Regex failed to compile: %d\n", rv); regfree(&re_simple_c); regfree(&re_gas_c); return MRV_GENERAL_ERROR; } /* Parse the telegram */ LL_FOREACH(telegram, telegram_it) { if (next_is_gas) { next_is_gas = 0; if ((rv = regexec(&re_gas_c, telegram_it->t_line, 2, gas_m, 0)) == 0) { size_t val_len = gas_m[1].rm_eo - gas_m[1].rm_so; char val_buf[256] = { 0 }; smart_counter* new_counter = NULL; if (val_len >= 256) { ERROR_MSG("Invalid gas counter data of length %zd", val_len); } else { /* Copy value */ strncpy(val_buf, &telegram_it->t_line[gas_m[1].rm_so], val_len); /* Add new counter */ new_counter = (smart_counter*) malloc(sizeof(smart_counter)); if (new_counter == NULL) { regfree(&re_simple_c); regfree(&re_gas_c); regfree(&re_counterval_c); /* Return memory error */ return MRV_MEMORY; } new_counter->id = strdup(gas_id); new_counter->unit = strdup(UNIT_M3); new_counter->value = strtold(val_buf, NULL); LL_APPEND((*counters), new_counter); } } } else if ((rv = regexec(&re_simple_c, telegram_it->t_line, 3, simple_m, 0)) == 0) { size_t id_len = simple_m[1].rm_eo - simple_m[1].rm_so; size_t val_len = simple_m[2].rm_eo - simple_m[2].rm_so; smart_counter* new_counter = NULL; char* new_id = (char*) malloc((id_len + 1) * sizeof(char)); char* new_val = NULL; if (new_id == NULL) { /* Return memory error */ regfree(&re_simple_c); regfree(&re_gas_c); regfree(&re_counterval_c); return MRV_MEMORY; } /* First, copy the ID of the counter so we can check if this is a gas meter */ memset(new_id, 0, id_len + 1); strncpy(new_id, &telegram_it->t_line[simple_m[1].rm_so], id_len); if ((gas_id != NULL) && (strlen(gas_id) == id_len) && (strcmp(gas_id, new_id) == 0)) { /* This is a gas meter counter, the actual value is on the next line */ next_is_gas = 1; free(new_id); } else { /* This is a regular counter */ new_val = (char*) malloc((val_len + 1) * sizeof(char)); if (new_val == NULL) { /* Return memory error */ free(new_id); regfree(&re_simple_c); regfree(&re_gas_c); regfree(&re_counterval_c); return MRV_MEMORY; } memset(new_val, 0, val_len + 1); strncpy(new_val, &telegram_it->t_line[simple_m[2].rm_so], val_len); /* Match the value */ if ((rv = regexec(&re_counterval_c, new_val, 3, counterval_m, 0)) == 0) { size_t ctr_len = counterval_m[1].rm_eo - counterval_m[1].rm_so; size_t unit_len = counterval_m[2].rm_eo - counterval_m[2].rm_so; char ctr_buf[256] = { 0 }; char unit_buf[256] = { 0 }; if ((ctr_len >= 256) || (unit_len >= 256)) { ERROR_MSG("Invalid counter ID (%zd bytes) or unit (%zd bytes) length", ctr_len, unit_len); } else { /* Copy counter value and unit information */ strncpy(ctr_buf, &new_val[counterval_m[1].rm_so], ctr_len); strncpy(unit_buf, &new_val[counterval_m[2].rm_so], unit_len); /* Add this new counter to the list */ new_counter = (smart_counter*) malloc(sizeof(smart_counter)); if (new_counter == NULL) { /* Return memory error! */ regfree(&re_simple_c); regfree(&re_gas_c); regfree(&re_counterval_c); free(new_id); free(new_val); return MRV_MEMORY; } new_counter->unit = strdup(unit_buf); new_counter->id = new_id; new_counter->value = strtold(&ctr_buf[0], NULL); LL_APPEND((*counters), new_counter); } } else { free(new_id); } free(new_val); } } } /* Clean up regular expression parser */ regfree(&re_simple_c); regfree(&re_gas_c); regfree(&re_counterval_c); return 0; }
obj* php_load_impl(const char* base, const char*& beg, const char* end) { #define THROW_INPUT_ERROR2(msg, ptr) \ do{ char buf[256]; \ int blen = snprintf(buf, sizeof(buf), "%s at pos: %ld", msg, long(ptr-base)); \ std::string strMsg(buf, blen); \ throw std::logic_error(strMsg); \ } while (0) #define THROW_INPUT_ERROR(msg) THROW_INPUT_ERROR2(msg, beg) switch (*beg) { default: { std::string msg = "php_load: invalid type: "; msg.push_back(*beg); msg += ", input:"; msg.append(beg, std::min<size_t>(100, end-beg)); throw std::logic_error(msg); } case 'i': { // i:val; if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php integer"); if (':' != *beg) THROW_INPUT_ERROR("php_load: integer, expect ':'"); char* pp = NULL; long long val = strtoll(beg+1, &pp, 10); if (';' != *pp) THROW_INPUT_ERROR2("php_load: integer, expect ';'", pp); beg = pp + 1; if (sizeof(long) == sizeof(long long) || (LONG_MIN <= val&&val <= LONG_MAX)) return new obj_long((long)val); else return new obj_llong(val); } case 'b': { // b:val; if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php boolean"); if (':' != *beg) THROW_INPUT_ERROR("php_load: boolean, expect ':'"); char* pp = NULL; long val = strtol(beg+1, &pp, 10); if (';' != *pp) THROW_INPUT_ERROR2("php_load: boolean, expect ';'", pp); beg = pp + 1; return new obj_bool(val ? 1 : 0); } #if 0 case 'd': { // d:val; if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php double"); if (':' != *beg) THROW_INPUT_ERROR("php_load: double, expect ':'"); char* pp = NULL; double val = strtod(beg+1, &pp); if (';' != *pp) THROW_INPUT_ERROR("php_load: double, expect ';'"); beg = pp + 1; return new obj_double(val); } #else case 'd': { // d:val; if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php double"); if (':' != *beg) THROW_INPUT_ERROR("php_load: long double, expect ':'"); char* pp = NULL; #ifdef __CYGWIN__ //_LDBL_EQ_DBL double val = strtod(beg+1, &pp); #else long double val = strtold(beg+1, &pp); #endif if (';' != *pp) THROW_INPUT_ERROR2("php_load: long double, expect ';'", pp); beg = pp + 1; return new obj_ldouble(val); } #endif case 's': { // s:size:"content"; if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php string"); if (':' != *beg) THROW_INPUT_ERROR("php_load: string.size expect ':'"); char* pp = NULL; long len = strtol(beg+1, &pp, 10); if (':' != *pp) THROW_INPUT_ERROR2("php_load: string.content expect ':'", pp); if (len < 0) THROW_INPUT_ERROR2("php_load: string.size is negtive", beg+1); if ('"' != pp[1]) THROW_INPUT_ERROR2("php_load: string.content expect '\"'", pp+1); if ('"' != pp[len+2]) THROW_INPUT_ERROR2("php_load: string.content not found right quote", pp+len+2); if (';' != pp[len+3]) THROW_INPUT_ERROR2("php_load: string didn't end with ';'", pp+len+3); std::auto_ptr<obj_string> x(new obj_string); x->resize(len); x->assign(pp+2, len); beg = pp + len + 4; // s:size:"content"; return x.release(); } case 'a': { // A:size:{key;value; ....} // fprintf(stderr, "loading array: "); if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php array"); if (':' != *beg) THROW_INPUT_ERROR("php_load: array.size expect ':'"); char* pp = NULL; long len = strtol(beg+1, &pp, 10); // fprintf(stderr, "size=%ld\n", len); if (':' != pp[0] || '{' != pp[1]) THROW_INPUT_ERROR2("php_load: array.size should followed by ':{'", pp); std::auto_ptr<obj_array> arr(new obj_array); std::auto_ptr<php_array> map; arr->resize(2*len); beg = pp + 2; long max_idx = -1; for (long i = 0; i < len; ++i) { // fprintf(stderr, "loading array[%ld]:\n", i); const char* key_pos = beg; std::auto_ptr<obj> key(php_load_impl(base, beg, end)); if (key.get() == NULL) { THROW_INPUT_ERROR2("php_load: array.key must not be NULL", key_pos); } if (arr.get()) { obj_long* l = dynamic_cast<obj_long*>(key.get()); if (l) { long idx = l->t; if (idx >= 0 && idx < (long)arr->size()) { (*arr)[idx].reset(php_load_impl(base, beg, end)); max_idx = std::max(idx, max_idx); continue; } } } if (map.get() == NULL) map.reset(new php_array); if (arr.get()) { for (long j = 0; j <= max_idx; ++j) { if ((*arr)[j]) (*map)[obj_ptr(new obj_long(j))] = (*arr)[j]; } arr.reset(NULL); } (*map)[obj_ptr(key.get())].reset(php_load_impl(base, beg, end)); key.release(); } if ('}' != *beg) THROW_INPUT_ERROR("php_load: array not correctly closed"); beg += 1; if (arr.get()) { arr->resize(max_idx+1); arr->shrink_to_fit(); return arr.release(); } return map.release(); } case 'N': { if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php NULL"); if (';' != *beg) THROW_INPUT_ERROR("php_load: NULL expect ';'"); beg += 1; return NULL; } case 'O': { // O:strlen(class name):"class name":fields_num:{s:strlen(field name):"field name":field definition;(repeated per field)} if (++beg >= end) THROW_INPUT_ERROR("php_load: Incompleted php Object"); if (':' != *beg) THROW_INPUT_ERROR("php_load: Object.namelen expect ':' 1"); char* pp = NULL; long len = strtol(beg+1, &pp, 10); if (':' != pp[0] && '"' != pp[1]) THROW_INPUT_ERROR2("php_load: Object.namelen expect ':\"' 2", pp); if (pp + 4 + len > end) THROW_INPUT_ERROR2("php_load: Object 3", pp); std::auto_ptr<php_object> tree(new php_object); tree->cls_name.assign(pp + 2, len); long fields = strtol(pp + 4 + len, &pp, 10); if (':' != pp[0] || '{' != pp[1]) THROW_INPUT_ERROR2("php_load: Object 4", pp); beg = pp + 2; for (long i = 0; i < fields; ++i) { std::auto_ptr<obj> pname(php_load_impl(base, beg, end)); obj_string* name = dynamic_cast<obj_string*>(pname.get()); if (NULL == name) THROW_INPUT_ERROR("object field name is not a string"); std::auto_ptr<obj> value(php_load_impl(base, beg, end)); tree->fields[*name].reset(value.release()); } if ('}' != beg[0]) THROW_INPUT_ERROR("php_load: Object not correctly closed"); beg += 1; return tree.release(); } } assert(0); return NULL; }
TEST(d == 1.0, "atof(1.0) == 1.0"); TEST_TRACE(C99 7.20.1.2) i = atoi("1234"); TEST(i == 1234, "atoi(1234) == 1234"); l = atol("12345678"); TEST(l == 12345678L, "atol(12345678L) == 12345678L"); ll = atoll("12345678901234"); TEST(ll == 12345678901234LL, "atoll(12345678901234LL) == 12345678901234LL"); TEST_TRACE(C99 7.20.1.3) d = strtod("1.0", &p); TEST(d == 1.0 && *p == '\0', "strtod(1.0) == 1.0"); f = strtof("1.0", &p); TEST_RESOLVED(ARMEB, "http://ellcc.org/bugzilla/show_bug.cgi?id=56") TEST(f == 1.0F && *p == '\0', "strtof(1.0) == 1.0F (%g)", f); TEST_FAIL(ARMEB, f == 1.0F && *p == '\0', "strtof(1.0) == 1.0F (%g)", f); ld = strtold("1.0", &p); TEST_EXCLUDE(PPC, "http://ellcc.org/bugzilla/show_bug.cgi?id=47") TEST_EXCLUDE(PPC64, "http://ellcc.org/bugzilla/show_bug.cgi?id=47") TEST(ld == 1.0L && *p == '\0', "strtold(1.0) == 1.0L"); TEST_FAIL(PPC, ld == 1.0L && *p == '\0', "strtold(1.0) == 1.0L"); TEST_FAIL(PPC64, ld == 1.0L && *p == '\0', "strtold(1.0) == 1.0L"); TEST_TRACE(C99 7.20.1.4) l = strtol("12345678", &p, 0); TEST(l == 12345678L && *p == '\0', "strtol(12345678L) == 12345678L"); ul = strtoul("12345678", &p, 0); TEST(ul == 12345678UL && *p == '\0', "strtoul(12345678UL) == 12345678UL"); ll = strtoll("12345678901234", &p, 0); TEST(ll == 12345678901234LL && *p == '\0', "strtoll(12345678901234LL) == 12345678901234LL"); ull = strtoull("12345678901234", &p, 0); TEST(ull == 12345678901234LL && *p == '\0', "strtoull(12345678901234LL) == 12345678901234LL"); TEST_TRACE(C99 7.20.2.1)
double strtod(const char *nptr, char **endptr) { return strtold(nptr, endptr); }
void ShmemServer::handle_conn() { #ifndef NDEBUG std::cout << "DEBUG" << ": got IR" << std::endl; #endif // initialize backend with received IR auto backend = parseIRtoBackend((char *) shmemptr); *(long *)shmemptr = TimeDiffOpt.count(); *(((long *)shmemptr) + 1) = TimeDiffInit.count(); // signal to client: got IR, ready to get calls, time measures in shmem sem_post(shmem_sem); while (1) { sem_wait(shmem_force_order_sem); // wait for call sem_wait(shmem_sem); sem_post(shmem_force_order_sem); #ifndef NDEBUG std::cout << "DEBUG" << ": got call \n"; #endif // check for exit symbol if (((char *)shmemptr)[0] == ';') { #ifndef NDEBUG std::cout << "DEBUG" << ": found exit symbol \n"; #endif break; } llvm::Function* calledFunction = nullptr; std::vector<llvm::GenericValue> args; std::list<std::vector<llvm::GenericValue>::size_type> indexesOfPointersInArgs; llvm::GenericValue result = handleCall(backend.get(), (char *) shmemptr, calledFunction, args, indexesOfPointersInArgs); auto shmempos = shmemptr; // write measured time to memory *(long *)shmempos = TimeDiffLastExecution.count(); shmempos = (long *)shmempos + 1; // write changes to args and result back to shared memory for (const auto& indexOfPtr : indexesOfPointersInArgs) { auto paramType = calledFunction->getFunctionType()->getParamType(indexOfPtr); while (paramType->getTypeID() == llvm::Type::ArrayTyID || paramType->getTypeID() == llvm::Type::PointerTyID) paramType = llvm::cast<llvm::SequentialType>(paramType)->getElementType(); if (paramType->getTypeID() == llvm::Type::IntegerTyID) { ShmemHelperFunctions::marshallArrayOfSizeAndTypeIntoMemory(args[indexOfPtr].PointerVal, args[indexOfPtr+1].IntVal.getSExtValue(), std::pair<llvm::Type::TypeID, unsigned>(paramType->getTypeID(), ((llvm::IntegerType*)paramType)->getBitWidth()), shmempos); } else ShmemHelperFunctions::marshallArrayOfSizeAndTypeIntoMemory(args[indexOfPtr].PointerVal, args[indexOfPtr+1].IntVal.getSExtValue(), std::pair<llvm::Type::TypeID, unsigned>(paramType->getTypeID(), 0U), shmempos); free(args[indexOfPtr].PointerVal); } switch (calledFunction->getReturnType()->getTypeID()) { case llvm::Type::VoidTyID: // void return break; case llvm::Type::FloatTyID: *(float *)shmempos = result.FloatVal; break; case llvm::Type::DoubleTyID: *(double *)shmempos = result.DoubleVal; break; case llvm::Type::X86_FP80TyID: { char tmpHexString[64]; llvm::APFloat(llvm::APFloat::x87DoubleExtended, result.IntVal).convertToHexString(tmpHexString, 0U, false, llvm::APFloat::roundingMode::rmNearestTiesToEven); *(long double *)shmempos = strtold(tmpHexString, nullptr); break; } case llvm::Type::FP128TyID: { char tmpHexString[64]; llvm::APFloat(llvm::APFloat::IEEEquad, result.IntVal).convertToHexString(tmpHexString, 0U, false, llvm::APFloat::roundingMode::rmNearestTiesToEven); *(long double *)shmempos = strtold(tmpHexString, nullptr); break; } case llvm::Type::IntegerTyID: // Note: LLVM does not differentiate between signed/unsiged int types switch (result.IntVal.getBitWidth()) { case 8: *(uint8_t *)shmempos = (uint8_t) result.IntVal.getZExtValue(); break; case 16: *(uint16_t *)shmempos = (uint16_t) result.IntVal.getZExtValue(); break; case 32: *(uint32_t *)shmempos = (uint32_t) result.IntVal.getZExtValue(); break; case 64: *(uint64_t *)shmempos = (uint64_t) result.IntVal.getZExtValue(); break; default: error(std::string("ERROR, integer bitwidth of " + std::to_string(result.IntVal.getBitWidth()) + " not supported").c_str()); } break; default: error(std::string("ERROR, LLVM TypeID " + std::to_string(calledFunction->getReturnType()->getTypeID()) + " of result of function \"" + calledFunction->getName().str() + "\" is not supported").c_str()); } #ifndef NDEBUG std::cout << "DEBUG" << ": signaling 'result is ready' to client \n"; #endif sem_post(shmem_sem); } }
long double getProperty_LongDouble(const char *key, const long double defaultVal) { char *val = (char *) HashMap_get(_sdf_globalPropertiesMap, key); return ((val) ? strtold(val, NULL) : defaultVal); }
int psrfits_write_ephem(struct psrfits *pf, FILE *parfile) { // Read a pulsar ephemeris (par file) and put it into // the psrfits PSREPHEM table. Only minimal checking // is done. // Get status int *status = &(pf->status); // Save current HDU, move to psrephem table int hdu; fits_get_hdu_num(pf->fptr, &hdu); fits_movnam_hdu(pf->fptr, BINARY_TBL, "PSREPHEM", 0, status); // Loop over lines in par file int row=1, col, dtype; double dval; int ival; long double ldval; char line[256], *ptr, *saveptr, *key, *val; while (fgets(line, 256, parfile)!=NULL) { // Convert tabs to spaces while ((ptr=strchr(line,'\t'))!=NULL) { *ptr=' '; } // strip leading whitespace ptr = line; while (*ptr==' ') { ptr++; } // Identify comments or blank lines if (line[0]=='\n' || line[0]=='#' || (line[0]=='C' && line[1]==' ')) continue; // Split into key/val (ignore fit flag and error) key = strtok_r(line, " ", &saveptr); val = strtok_r(NULL, " ", &saveptr); if (key==NULL || val==NULL) continue; // TODO : complain? // Deal with any special cases here if (strncmp(key, "PSR", 3)==0) { // PSR(J) -> PSR_NAME fits_get_colnum(pf->fptr,CASEINSEN,"PSR_NAME",&col,status); fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status); } else if (strncmp(key, "RA", 2)==0) { // RA -> RAJ fits_get_colnum(pf->fptr,CASEINSEN,"RAJ",&col,status); fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status); } else if (strncmp(key, "DEC", 3)==0) { // DEC -> DECJ fits_get_colnum(pf->fptr,CASEINSEN,"DECJ",&col,status); fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status); } else if (key[0]=='E' && key[1]=='\0') { // E -> ECC dval = atof(val); fits_get_colnum(pf->fptr,CASEINSEN,"ECC",&col,status); fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status); } else if (strncmp(key, "F0", 2)==0) { // F is converted to mHz and split into int/frac ldval = strtold(val,NULL) * 1000.0; // Hz->mHz ival = (int)ldval; dval = ldval - (long double)ival; fits_get_colnum(pf->fptr,CASEINSEN,"IF0",&col,status); fits_write_col(pf->fptr,TINT,col,row,1,1,&ival,status); fits_get_colnum(pf->fptr,CASEINSEN,"FF0",&col,status); fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status); } else if (strncmp(key, "TZRMJD", 6)==0) { // TZRMJD is split into int/frac ldval = strtold(val,NULL); ival = (int)ldval; dval = ldval - (long double)ival; fits_get_colnum(pf->fptr,CASEINSEN,"TZRIMJD",&col,status); fits_write_col(pf->fptr,TINT,col,row,1,1,&ival,status); fits_get_colnum(pf->fptr,CASEINSEN,"TZRFMJD",&col,status); fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status); } else { // Find column, skip/warn if this one isn't present fits_get_colnum(pf->fptr,CASEINSEN,key,&col,status); if (*status==COL_NOT_FOUND) { #if (DEBUGOUT) fprintf(stderr, "psrfits_write_epherm warning: Couldn't find keyword %s " "in ephemeris table.\n", key); #endif *status=0; continue; } // Need to convert string to appropriate column data type // and then write it to the column. These should all be // either double int or string. fits_get_coltype(pf->fptr,col,&dtype,NULL,NULL,status); if (dtype==TDOUBLE || dtype==TFLOAT) { dval = atof(val); fits_write_col(pf->fptr,TDOUBLE,col,row,1,1,&dval,status); } else if (dtype==TINT || dtype==TLONG || dtype==TSHORT) { ival = atoi(val); fits_write_col(pf->fptr,TINT,col,row,1,1,&ival,status); } else if (dtype==TSTRING) { fits_write_col(pf->fptr,TSTRING,col,row,1,1,&val,status); } else { fprintf(stderr, "psrfits_write_ephem warning: " "Unhandled column datatype (key=%s)\n", key); continue; } } // sucess/failure if (*status) { fprintf(stderr, "psrfits_write_ephem failed: key=%s val=%s\n", key, val); fits_report_error(stderr, *status); *status=0; } #if 0 // DEBUG else { fprintf(stderr, "psrfits_write_ephem success: key=%s val=%s\n", key, val); } #endif } // Go back to orig HDU fits_movabs_hdu(pf->fptr, hdu, NULL, status); return *status; }
static inline int process_number_token(JSONRD_T *jsonrd, const char *chunk, size_t size, size_t offset) { int i; for (i = offset; i < size; i++) { switch (jsonrd->token.num_state) { case NS_BEGIN: if (chunk[i] == '-') { jsonrd->token.num_state = NS_LEADING_MINUS; } else if (chunk[i] == '0') { jsonrd->token.num_state = NS_LEADING_ZERO; } else if (chunk[i] > '0' && chunk[i] <= '9') { jsonrd->token.num_state = NS_LEADING_DIGITS; } else { jsonrd->token.type = TOK_ILLEGAL; jsonrd->token.state = TS_FOUND_TOKEN; return i + 1; } break; case NS_LEADING_MINUS: if (chunk[i] == '0') { jsonrd->token.num_state = NS_LEADING_ZERO; } else if (chunk[i] > '0' && chunk[i] <= '9') { jsonrd->token.num_state = NS_LEADING_DIGITS; } else { jsonrd->token.type = TOK_ILLEGAL; jsonrd->token.state = TS_FOUND_TOKEN; return i + 1; } break; case NS_LEADING_ZERO: if (chunk[i] == '.') { jsonrd->token.num_state = NS_DECIMAL_PLACE; } else if (chunk[i] == 'e' || chunk[i] == 'E') { jsonrd->token.num_state = NS_EXPONENT_CHAR; } else { jsonrd->token.value_number = strtold(str_internal(jsonrd->buf), NULL); jsonrd->token.state = TS_FOUND_TOKEN; return i; } break; case NS_LEADING_DIGITS: if (chunk[i] >= '0' && chunk[i] <= '9') { // keep current state } else if (chunk[i] == '.') { jsonrd->token.num_state = NS_DECIMAL_PLACE; } else if (chunk[i] == 'e' || chunk[i] == 'E') { jsonrd->token.num_state = NS_EXPONENT_CHAR; } else { jsonrd->token.value_number = strtold(str_internal(jsonrd->buf), NULL); jsonrd->token.state = TS_FOUND_TOKEN; return i; } break; case NS_DECIMAL_PLACE: if (chunk[i] >= '0' && chunk[i] <= '9') { jsonrd->token.num_state = NS_DECIMAL_DIGITS; } else { jsonrd->token.type = TOK_ILLEGAL; jsonrd->token.state = TS_FOUND_TOKEN; return i + 1; } break; case NS_DECIMAL_DIGITS: if (chunk[i] >= '0' && chunk[i] <= '9') { // keep current state } else if (chunk[i] == 'e' || chunk[i] == 'E') { jsonrd->token.num_state = NS_EXPONENT_CHAR; } else { jsonrd->token.value_number = strtold(str_internal(jsonrd->buf), NULL); jsonrd->token.state = TS_FOUND_TOKEN; return i; } break; case NS_EXPONENT_CHAR: if (chunk[i] == '+' || chunk[i] == '-') { jsonrd->token.num_state = NS_EXPONENT_SIGN; } else if (chunk[i] >= '0' && chunk[i] <= '9') { jsonrd->token.num_state = NS_EXPONENT_DIGITS; } else { jsonrd->token.type = TOK_ILLEGAL; jsonrd->token.state = TS_FOUND_TOKEN; return i + 1; } break; case NS_EXPONENT_SIGN: if (chunk[i] >= '0' && chunk[i] <= '9') { jsonrd->token.num_state = NS_EXPONENT_DIGITS; } else { jsonrd->token.type = TOK_ILLEGAL; jsonrd->token.state = TS_FOUND_TOKEN; return i + 1; } break; case NS_EXPONENT_DIGITS: if (chunk[i] >= '0' && chunk[i] <= '9') { // keep current state } else { jsonrd->token.value_number = strtold(str_internal(jsonrd->buf), NULL); jsonrd->token.state = TS_FOUND_TOKEN; return i; } break; default: die("Illegal state"); return size; } str_append(jsonrd->buf, chunk+i, 1); } return size; }
unsigned int parse_memory_size(const char *sizeName, /* "initial heap" or "maximum heap" or "initial stack" or "maximum stack" */ const char *sizeFlag, // "-Xms" or "-Xmx" or // "-Xss" or "-Xsg" or "-Xsx" const char *defaultFactor, // We now always default to bytes ("") unsigned roundTo, // Round to PAGE_SIZE_BYTES or to 4. const char *token /* e.g., "-Xms200M" or "-Xms200" */, const char *subtoken /* e.g., "200M" or "200" */, bool *fastExit) { errno = 0; long double userNum; char *endp; /* Should be const char *, but if we do that, then the C++ compiler complains about the prototype for strtold() or strtod(). This is probably a bug in the specification of the prototype. */ userNum = strtold(subtoken, &endp); if (endp == subtoken) { fprintf(SysTraceFile, "%s: \"%s\": -X%s must be followed by a number.\n", Me, token, sizeFlag); *fastExit = true; } // First, set the factor appropriately, and make sure there aren't extra // characters at the end of the line. const char *factorStr = defaultFactor; long double factor = 0.0; // 0.0 is a sentinel meaning Unset if (*endp == '\0') { /* no suffix. Along with the Sun JVM, we now assume Bytes by default. (This is a change from previous Jikes RVM behaviour.) */ factor = 1.0; } else if (strequal(endp, "pages") ) { factor = BYTES_IN_PAGE; /* Handle constructs like "M" and "K" */ } else if ( endp[1] == '\0' ) { factorStr = endp; } else { fprintf(SysTraceFile, "%s: \"%s\": I don't recognize \"%s\" as a" " unit of memory size\n", Me, token, endp); *fastExit = true; } if (! *fastExit && factor == 0.0) { char e = *factorStr; if (e == 'g' || e == 'G') factor = 1024.0 * 1024.0 * 1024.0; else if (e == 'm' || e == 'M') factor = 1024.0 * 1024.0; else if (e == 'k' || e == 'K') factor = 1024.0; else if (e == '\0') factor = 1.0; else { fprintf(SysTraceFile, "%s: \"%s\": I don't recognize \"%s\" as a" " unit of memory size\n", Me, token, factorStr); *fastExit = true; } } // Note: on underflow, strtod() returns 0. if (!*fastExit) { if (userNum <= 0.0) { fprintf(SysTraceFile, "%s: You may not specify a %s %s;\n", Me, userNum < 0.0 ? "negative" : "zero", sizeName); fprintf(SysTraceFile, "\tit just doesn't make any sense.\n"); *fastExit = true; } } if (!*fastExit) { if ( errno == ERANGE || userNum > (((long double) (UINT_MAX - roundTo))/factor) ) { fprintf(SysTraceFile, "%s: \"%s\": out of range to represent internally\n", Me, subtoken); *fastExit = true; } } if (*fastExit) { fprintf(SysTraceFile, "\tPlease specify %s as follows:\n", sizeName); fprintf(SysTraceFile, "\t in bytes, using \"-X%s<positive number>\",\n", sizeFlag); fprintf(SysTraceFile, "\tor, in kilobytes, using \"-X%s<positive number>K\",\n", sizeFlag); fprintf(SysTraceFile, "\tor, in virtual memory pages of %u bytes, using\n" "\t\t\"-X%s<positive number>pages\",\n", BYTES_IN_PAGE, sizeFlag); fprintf(SysTraceFile, "\tor, in megabytes, using \"-X%s<positive number>M\",\n", sizeFlag); fprintf(SysTraceFile, "\tor, in gigabytes, using \"-X%s<positive number>G\"\n", sizeFlag); fprintf(SysTraceFile, " <positive number> can be a floating point value or a hex value like 0x10cafe0.\n"); if (roundTo != 1) { fprintf(SysTraceFile, " The # of bytes will be rounded up to a multiple of"); if (roundTo == BYTES_IN_PAGE) fprintf(SysTraceFile, "\n the virtual memory page size: "); fprintf(SysTraceFile, "%u\n", roundTo); } return 0U; // Distinguished value meaning trouble. } long double tot_d = userNum * factor; assert(tot_d <= (UINT_MAX - roundTo)); assert(tot_d >= 1); unsigned tot = (unsigned) tot_d; if (tot % roundTo) { unsigned newTot = tot + roundTo - (tot % roundTo); fprintf(SysTraceFile, "%s: Rounding up %s size from %u bytes to %u,\n" "\tthe next multiple of %u bytes%s\n", Me, sizeName, tot, newTot, roundTo, roundTo == BYTES_IN_PAGE ? ", the virtual memory page size" : ""); tot = newTot; } return tot; }
int main (int argc, char ** argv) { char buf[100]; register const struct ltest *lt; char *ep; int status = 0; int save_errno; for (lt = tests; lt->str != NULL; ++lt) { double d; errno = 0; d = strtod(lt->str, &ep); save_errno = errno; printf ("strtod (\"%s\") test %u", lt->str, (unsigned int) (lt - tests)); if (d == lt->expect && *ep == lt->left && save_errno == lt->err) puts ("\tOK"); else { puts ("\tBAD"); if (d != lt->expect) printf (" returns %.60g, expected %.60g\n", d, lt->expect); if (lt->left != *ep) { char exp1[5], exp2[5]; expand (exp1, *ep); expand (exp2, lt->left); printf (" leaves '%s', expected '%s'\n", exp1, exp2); } if (save_errno != lt->err) printf (" errno %d (%s) instead of %d (%s)\n", save_errno, strerror (save_errno), lt->err, strerror (lt->err)); status = 1; } } sprintf (buf, "%f", strtod ("-0.0", NULL)); if (strcmp (buf, "-0.000000") != 0) { printf (" strtod (\"-0.0\", NULL) returns \"%s\"\n", buf); status = 1; } const char input[] = "3752432815e-39"; float f1 = strtold (input, NULL); float f2; float f3 = strtof (input, NULL); sscanf (input, "%g", &f2); if (f1 != f2) { printf ("f1 = %a != f2 = %a\n", f1, f2); status = 1; } if (f1 != f3) { printf ("f1 = %a != f3 = %a\n", f1, f3); status = 1; } if (f2 != f3) { printf ("f2 = %a != f3 = %a\n", f2, f3); status = 1; } const char input2[] = "+1.000000000116415321826934814453125"; if (strtold (input2, NULL) != +1.000000000116415321826934814453125L) { printf ("input2: %La != %La\n", strtold (input2, NULL), +1.000000000116415321826934814453125L); status = 1; } status |= long_dbl (); status |= locale_test (); return status ? EXIT_FAILURE : EXIT_SUCCESS; }
TEST(stdlib, strtold) { ASSERT_DOUBLE_EQ(1.23, strtold("1.23", NULL)); }
/* * Function: pg_get_result * * Executes a PostgreSQL Query using connection details from a Zabbix agent * request structure and updates the agent result structure with the value of * the first column of the first row returned. * * type may be * * Query parameters may be provided as a NULL terminated sequence of *char * values in the ... parameter. * * Parameter [request]: Zabbix agent request structure. * Passed to pg_connect to fetch as valid PostgreSQL * server connection * * Parameter [result]: Zabbix agent result structure * * Parameter [type]: Result type to set. May be one of AR_STRING, AR_UINT64 * or AR_DOUBLE. * * Paramater [query]: PostgreSQL query to execute. Query should return a * single scalar string value. Parameters defined using PostgreSQL's * '$n' notation will be replaced with the corresponding variadic * argument provided in ... * * Returns: SYSINFO_RET_OK or SYSINFO_RET_FAIL on error */ int pg_get_result(AGENT_REQUEST *request, AGENT_RESULT *result, int type, const char *query, PGparams params) { int ret = SYSINFO_RET_FAIL; // Request result code const char *__function_name = "pg_get_result"; // Function name for log file PGconn *conn = NULL; PGresult *res = NULL; char *value = NULL; zabbix_log(LOG_LEVEL_DEBUG, "In %s(%s)", __function_name, request->key); // Connect to PostreSQL if(NULL == (conn = pg_connect(request))) goto out; // Execute a query res = pg_exec(conn, query, params); if(PQresultStatus(res) != PGRES_TUPLES_OK) { zabbix_log(LOG_LEVEL_ERR, "Failed to execute PostgreSQL query in %s(%s) with: %s", __function_name, request->key, PQresultErrorMessage(res)); goto out; } if(0 == PQntuples(res)) { zabbix_log(LOG_LEVEL_DEBUG, "No results returned for query \"%s\" in %s(%s)", query, __function_name, request->key); goto out; } // get scalar value (freed later by PQclear) value = PQgetvalue(res, 0, 0); // Set result switch(type) { case AR_STRING: // string result (zabbix will clean the strdup'd buffer) SET_STR_RESULT(result, strdup(value)); break; case AR_UINT64: // integer result // Convert E Notation if(1 < strlen(value) && '.' == value[1]) { double dbl = strtod(value, NULL); SET_UI64_RESULT(result, (unsigned long long) dbl); } else { SET_UI64_RESULT(result, strtoull(value, NULL, 10)); } break; case AR_DOUBLE: // double result SET_DBL_RESULT(result, strtold(value, NULL)); break; default: // unknown result type zabbix_log(LOG_LEVEL_ERR, "Unsupported result type: 0x%0X in %s", type, __function_name); goto out; } ret = SYSINFO_RET_OK; out: PQclear(res); PQfinish(conn); zabbix_log(LOG_LEVEL_DEBUG, "End of %s(%s)", __function_name, request->key); return ret; }
static int test (const char str[]) { char *endp; int result = 0; puts (str); double d = strtod (str, &endp); if (!isnan (d)) { puts ("strtod did not return NAN"); result = 1; } if (issignaling (d)) { puts ("strtod returned a sNAN"); result = 1; } if (strcmp (endp, "something") != 0) { puts ("strtod set incorrect end pointer"); result = 1; } float f = strtof (str, &endp); if (!isnanf (f)) { puts ("strtof did not return NAN"); result = 1; } if (issignaling (f)) { puts ("strtof returned a sNAN"); result = 1; } if (strcmp (endp, "something") != 0) { puts ("strtof set incorrect end pointer"); result = 1; } long double ld = strtold (str, &endp); if (!isnan (ld)) { puts ("strtold did not return NAN"); result = 1; } if (issignaling (ld)) { puts ("strtold returned a sNAN"); result = 1; } if (strcmp (endp, "something") != 0) { puts ("strtold set incorrect end pointer"); result = 1; } return result; }