static float recalllara( char **mseq1, char **mseq2, int alloclen ) { static FILE *fp = NULL; static char *ungap1; static char *ungap2; static char *ori1; static char *ori2; int res; static char com[10000]; float value; if( fp == NULL ) { fp = fopen( "_laraout", "r" ); if( fp == NULL ) { fprintf( stderr, "Cannot open _laraout\n" ); exit( 1 ); } ungap1 = AllocateCharVec( alloclen ); ungap2 = AllocateCharVec( alloclen ); ori1 = AllocateCharVec( alloclen ); ori2 = AllocateCharVec( alloclen ); } strcpy( ori1, *mseq1 ); strcpy( ori2, *mseq2 ); fgets( com, 999, fp ); myfgets( com, 9999, fp ); strcpy( *mseq1, com ); myfgets( com, 9999, fp ); strcpy( *mseq2, com ); gappick0( ungap1, *mseq1 ); gappick0( ungap2, *mseq2 ); t2u( ungap1 ); t2u( ungap2 ); if( strcmp( ungap1, ori1 ) || strcmp( ungap2, ori2 ) ) { fprintf( stderr, "SEQUENCE CHANGED!!\n" ); fprintf( stderr, "*mseq1 = %s\n", *mseq1 ); fprintf( stderr, "ungap1 = %s\n", ungap1 ); fprintf( stderr, "ori1 = %s\n", ori1 ); fprintf( stderr, "*mseq2 = %s\n", *mseq2 ); fprintf( stderr, "ungap2 = %s\n", ungap2 ); fprintf( stderr, "ori2 = %s\n", ori2 ); exit( 1 ); } value = (float)naivepairscore11( *mseq1, *mseq2, penalty ); // fclose( fp ); // saigo dake yatta houga yoi. return( value ); }
/* Lockup an entry in a file Return all the lines between the entry and the next one or the end of file An entry is something between braces. */ static void lookup_entry(FILE *fichier,char *chaine) { int found=0,pointeur=0,i=0; char *temp,*temp2; temp=(char *)malloc(sizeof(pstring)); temp2=(char *)malloc(sizeof(pstring)); if(temp == NULL || temp2 == NULL) { fprintf(stderr,"lookup_entry: malloc fail !\n"); exit(1); } *buffer[0]='\0'; pstrcpy(temp2,"["); pstrcat(temp2,chaine); pstrcat(temp2,"]"); rewind(fichier); #ifdef DEBUGIT fprintf(stderr,"\tLooking for %s\n",chaine); #endif while (!feof(fichier) && found==0) { *temp='\0'; myfgets(temp,255,fichier); if (strncmp(temp,temp2,strlen(temp2))==0) found=1; } while (!feof(fichier) && found==1) { *temp='\0'; myfgets(temp,255,fichier); if (*temp=='[') { found=2; *buffer[pointeur]='\0'; } else { pstrcpy(buffer[pointeur],temp); i=strlen(buffer[pointeur])-1; while (buffer[pointeur][i]=='\r' || buffer[pointeur][i]=='\n') buffer[pointeur][i--]='\0'; pointeur++; } } #ifdef DEBUGIT fprintf(stderr,"\t\tFound %d entries\n",pointeur-1); #endif }
void get_gcin_conf_str(char *name, char **rstr, char *default_str) { char fname[MAX_GCIN_STR]; char out[256]; if (*rstr) free(*rstr); get_gcin_conf_fname(name, fname); FILE *fp; if ((fp=fopen(fname, "rb")) == NULL) { *rstr = strdup(default_str); return; } myfgets(out, sizeof(out), fp); int len = strlen(out); if (len && out[len-1]=='\n') out[len-1] = 0; fclose(fp); *rstr = strdup(out); }
void load_phrase(char *fname, time_t *modtime, struct keystruc *tr, int trN) { FILE *fp; char kname[32]; char ttt[512]; // dbg("load_phrase %s\n", fname); if ((fp=watch_fopen(fname, modtime)) == NULL) { return; } // dbg("load succcc %s\n", fname); skip_utf8_sigature(fp); while (!feof(fp)) { int i,j; char str[512]; kname[0]=str[0]=0; myfgets(ttt, sizeof(ttt), fp); if (ttt[0]=='#') continue; for(i=0; ttt[i]!=' ' && ttt[i]!=9 && ttt[i]; i++) kname[i]=ttt[i]; kname[i]=0; gboolean is_upper = FALSE; if (!(kname[0]&0x80) && isupper(kname[0])) { is_upper = TRUE; kname[0] = tolower(kname[0]); } while((ttt[i]==' ' || ttt[i]==9) && ttt[i]) i++; for(j=0; ttt[i]!='\n' && ttt[i]; i++,j++) str[j]=ttt[i]; if (!str[0] || !kname[0]) continue; str[j]=0; for(i=0; i < trN; i++) if (!strcmp(kname, tr[i].kname)) break; if (i==trN) { dbg("unknown key: %s\n", kname); continue; } if (is_upper) tr[i].str_caps = strdup(str); else tr[i].str = strdup(str); } }
int main() { FILE *fp = fopen("test.dat", "r"); char *no = myfgets(fp); printf("%s", no); free(no); return 0; }
void readSourceFileLine(int *sourceAddressPtr, int *sourceDepthPtr, char *lineBuffer, FILE *file) { char c; *sourceAddressPtr = getw(file); *sourceDepthPtr = getw(file); myfgets(lineBuffer, LINE_BUFFER_SIZE, file); if (longLineFlag) { while ((c = getc(file)) != '\n' && c != EOF) ; lineBuffer[LINE_BUFFER_SIZE - 2] = '\n'; } }
static char *find_desc(FILE *fichier,char *text) { char *chaine; char *long_desc; char *short_desc; char *crap = NULL; char *p; int found=0; chaine=(char *)malloc(sizeof(pstring)); long_desc=(char *)malloc(sizeof(pstring)); short_desc=(char *)malloc(sizeof(pstring)); if (!chaine || !long_desc || !short_desc) { fprintf(stderr,"find_desc: Unable to malloc memory\n"); exit(1); } rewind(fichier); while (!feof(fichier) && found==0) { myfgets(chaine,255,fichier); long_desc=strtok(chaine,"="); crap=strtok(NULL,",\r"); p=long_desc; while(*p!='"' && *p!='\0') p++; if (*p=='"' && *(p+1)!='\0') p++; long_desc=p; if (*p!='\0') { p++; while(*p!='\"') p++; *p='\0'; } if (!strcmp(text,long_desc)) found=1; } free(chaine); if (!found || !crap) return(NULL); while(*crap==' ') crap++; pstrcpy(short_desc,crap); return(short_desc); }
int readAnotherLine(void) { int result; if (myfgets(lineBuffer, LINE_BUFFER_SIZE, input)) { if (amListing()) saveLineForListing(lineBuffer); lineBufferPtr = 1; result = lineBuffer[0]; } else { result = popInputFileStack(); } currentLineNumber++; cumulativeLineNumber++; return(result); }
int input_number_in_range(int from, int to) { int n; char *endptr; char input_buffer[128]; int first = 1; do { if (!first) { printf("Please enter number between %d and %d\n", from, to); } myfgets(input_buffer, 128); n = strtol(input_buffer, &endptr, 10); first = 0; } while (*endptr || n < from || n > to); return n; }
int confirm_choice(void) { char arg[3]; printf("Set (Y/N)\n"); while (1) { myfgets(arg, 3); if (arg[0] == 'Y' || arg[0] == 'y') { return 1; } if (arg[0] == 'N' || arg[0] == 'n') { return 0; } else { printf("Wrong key"); } } return 0; }
int add_patient(hospital_t * hosp, int num_of_hospitals) { int better_hosp_num = 0; person_t *patient; char input_buffer[128]; printf("Specify the surname of a patient(end, to exit): "); myfgets(input_buffer, 16); if (!(strcmp(input_buffer, "end"))) { printf("Shutdown\n"); return 0; } if (!(patient = (person_t *) malloc(sizeof(*patient)) )) { printf("Memory isn't allocated"); exit(1); } patient->next = NULL; strncpy(patient->surname, input_buffer, 16); printf("His coordinates:\n x = "); patient->coord.x = input_number_in_range(0, 180); printf(" y = "); patient->coord.y = input_number_in_range(0, 180); better_hosp_num = find_better_hospital(hosp, patient, num_of_hospitals); if (!better_hosp_num) { printf ("There is no places in hospitals, do you want to free some of it?\n"); if(confirm_choice()) { free_hospital_beds(hosp, num_of_hospitals); free(patient); return 1; } printf("Shutdown\n"); return 0; } place_patient_to_the_hospital(&hosp[better_hosp_num - 1], patient); hosp[better_hosp_num - 1].num_of_empty_beds--; return 1; }
static int rmailfunc(char *addrlist) { char *p, *p1; int r, noaddr=1; conf=0; cnews=0; debug(4, "rmailfunc(\"%s\")", addrlist); p=addrlist; while (isspace(*p)) p++; for (; *p; lseek(fileno(stdin), 0, SEEK_SET)) { for (p1=p; *p1 && !isspace(*p1); p1++); if (p1-p>=sizeof(addr)) { logwrite('?', "Too long address\n"); return 1; } strncpy(addr, p, (int)(p1-p)); addr[(int)(p1-p)]='\0'; ibufsrc=BUFSIZE; msgsize=-1; if (!myfgets(gotstr, sizeof(gotstr))) { logwrite('?', "Incorrect message\n"); return 1; } if (isbeg(gotstr)!=0) { logwrite('?', "Incorrect message start\n"); return 1; } r=msg_unmime(-1); if (r) return r; noaddr=0; for (p=p1; isspace(*p); p++); } debug(4, "rmailfunc ok"); return noaddr; }
void load_gtab_list(gboolean skip_disabled) { char ttt[128]; FILE *fp; get_hime_user_fname(gtab_list, ttt); if ((fp=fopen(ttt, "rb"))==NULL) { get_sys_table_file_name(gtab_list, ttt); if ((fp=fopen(ttt, "rb"))==NULL) p_err("cannot open %s", ttt); } dbg("load_gtab_list %s\n", ttt); skip_utf8_sigature(fp); int i; for (i=0; i < inmdN; i++) { INMD *pinmd = &inmd[i]; free(pinmd->filename); pinmd->filename=NULL; free(pinmd->cname); pinmd->cname=NULL; free(pinmd->icon); pinmd->icon=NULL; } inmdN = 0; char *def_file = strrchr(default_input_method_str, ' '); if (def_file) def_file++; while (!feof(fp)) { char line[256]; char name_ar[32], *name=name_ar; char key[32]; char file[32]; char icon[128]; inmd = trealloc(inmd, INMD, inmdN); name[0]=0; key[0]=0; file[0]=0; icon[0]=0; line[0]=0; myfgets(line, sizeof(line), fp); if (strlen(line) < 2) continue; if (line[0]=='#') continue; if (skip_disabled && line[0]=='!') continue; sscanf(line, "%s %s %s %s", name, key, file, icon); // dbg("%s %c\n", line, key[0]); if (strlen(name) < 1) break; int inmd_idx; INMD *pinmd = &inmd[inmd_idx = inmdN++]; bzero(pinmd, sizeof(INMD)); pinmd->key_ch = key[0]; pinmd->in_cycle = strchr(hime_str_im_cycle, key[0]) != NULL; // dbg("%d %d '%c'\n",inmdN, pinmd->in_cycle, pinmd->key_ch); if (!strcmp(file, "!ANTHY")) { strcpy(file, "anthy-module.so"); } if (!strcmp(file, "!INT_CODE")) { strcpy(file, "intcode-module.so"); } pinmd->filename = strdup(file); if (strstr(file, ".so") || strstr(file, ".dll")) { pinmd->method_type = method_type_MODULE; dbg("%s is module file\n", file); } else { int i; for(i=0; method_codes[i].id; i++) if (!strcmp(file, method_codes[i].id)) break; if (method_codes[i].id) pinmd->method_type = method_codes[i].method_type; } if (name[0]=='!') { name++; pinmd->disabled = TRUE; } if (default_input_method_str[0]==key[0] && !pinmd->disabled && (!def_file || !strcmp(file, def_file))) { default_input_method = inmd_idx; dbg("default_input_method %s %s %s %d\n", name, default_input_method_str, key, default_input_method); } pinmd->cname = strdup(name); if (strlen(icon)) pinmd->icon = strdup(icon); } fclose(fp); }
int main(int argc, char* argv[]) { InitModuleObjects(); StringBuffer passwd; if(argc < 2) { usage(); return -1; } else if (stricmp(argv[1], "-?") == 0 || stricmp(argv[1], "-h") == 0 || stricmp(argv[1], "-help") == 0) { usage(); return 0; } bool isBatchMode = false; MysslAction action = CRT; StringBuffer opfname, ocfname, orfname, cbuf, sbuf, lbuf, orgbuf, oubuf, cnbuf, ebuf, daysbuf, pfbuf, cfbuf, rfbuf, pbuf; int i; for (i=1; i<argc; i++) { if (stricmp(argv[i], "-crt") == 0) { action = CRT; } else if (stricmp(argv[i], "-csr") == 0) { action = CSR; } else if (stricmp(argv[i], "-sign") == 0) { action = SIGN; } else if (stricmp(argv[i], "-b") == 0) { isBatchMode = true; } else if(stricmp(argv[i], "-op") == 0) { i++; opfname.append(argv[i]); } else if(stricmp(argv[i], "-oc") == 0) { i++; ocfname.append(argv[i]); } else if(stricmp(argv[i], "-or") == 0) { i++; orfname.append(argv[i]); } else if(stricmp(argv[i], "-c") == 0) { i++; cbuf.append(argv[i]); } else if(stricmp(argv[i], "-s") == 0) { i++; sbuf.append(argv[i]); } else if(stricmp(argv[i], "-l") == 0) { i++; lbuf.append(argv[i]); } else if(stricmp(argv[i], "-org") == 0) { i++; orgbuf.append(argv[i]); } else if(stricmp(argv[i], "-ou") == 0) { i++; oubuf.append(argv[i]); } else if(stricmp(argv[i], "-cn") == 0) { i++; cnbuf.append(argv[i]); } else if(stricmp(argv[i], "-e") == 0) { i++; ebuf.append(argv[i]); } else if(stricmp(argv[i], "-days") == 0) { i++; daysbuf.append(argv[i]); } else if(stricmp(argv[i], "-ip") == 0) { i++; pfbuf.append(argv[i]); } else if(stricmp(argv[i], "-ic") == 0) { i++; cfbuf.append(argv[i]); } else if(stricmp(argv[i], "-ir") == 0) { i++; rfbuf.append(argv[i]); } else if(stricmp(argv[i], "-p") == 0) { i++; pbuf.append(argv[i]); } else { printf("unknown option %s\n", argv[i]); return -1; } } char buf[128]; if(!isBatchMode) { if(action == CSR || action == CRT) { if(cbuf.length() == 0) { printf("Country Name (2 letter code): "); myfgets(buf,128,stdin); if(*buf == '\0') strcpy(buf, "US"); cbuf.append(buf); } if(sbuf.length() == 0) { printf("State (full name): "); myfgets(buf,128,stdin); sbuf.append(buf); } if(lbuf.length() == 0) { printf("Locality Name (eg, city): "); myfgets(buf,128,stdin); lbuf.append(buf); } if(orgbuf.length() == 0) { printf("Organization Name (eg, company): "); myfgets(buf,128,stdin); orgbuf.append(buf); } if(oubuf.length() == 0) { printf("Organizational Unit Name: "); myfgets(buf,128,stdin); oubuf.append(buf); } if(ebuf.length() == 0) { printf("Email: "); myfgets(buf, 128, stdin); ebuf.append(buf); } if(cnbuf.length() == 0) { printf("Common Name (Server's hostname or IP address): "); myfgets(buf, 128, stdin); cnbuf.append(buf); } if(action == CRT) { printf("Number of days for the certificate to be valid: "); myfgets(buf, 128, stdin); if(strlen(buf) > 0) daysbuf.append(buf); printf("Private Key file(leave it blank if you want to generate a private key): "); myfgets(buf,128,stdin); pfbuf.append(buf); getpassword("Enter PEM pass phrase: ", pbuf); } else if(action == CSR) { printf("Private Key file(leave it blank if you want to generate a private key): "); myfgets(buf,128,stdin); pfbuf.append(buf); getpassword("Enter PEM pass phrase: ", pbuf); } } else if(action == SIGN) { printf("csr file: "); myfgets(buf,128,stdin); rfbuf.append(buf); printf("CA certificate file: "); myfgets(buf,128,stdin); cfbuf.append(buf); printf("CA privatekey file: "); myfgets(buf,128,stdin); pfbuf.append(buf); getpassword("CA private key passphrase: ", pbuf); printf("\nNumber of days for the certificate to be valid: "); myfgets(buf,128,stdin); daysbuf.append(buf); } } try { Owned<IFile> opf; Owned<IFileIO> opfio; if(opfname.length() > 0) { opf.setown(createIFile(opfname.str())); opfio.setown(opf->open(IFOcreate)); } Owned<IFile> ocf; Owned<IFileIO> ocfio; if(ocfname.length() > 0) { ocf.setown(createIFile(ocfname.str())); ocfio.setown(ocf->open(IFOcreate)); } Owned<IFile> orf; Owned<IFileIO> orfio; if(orfname.length() > 0) { orf.setown(createIFile(orfname.str())); orfio.setown(orf->open(IFOcreate)); } if(action == CRT || action == CSR) { Owned<ICertificate> cc = createCertificate(); if(cbuf.length() > 0) cc->setCountry(cbuf.str()); if(sbuf.length() > 0) cc->setState(sbuf.str()); if(lbuf.length() > 0) cc->setCity(lbuf.str()); if(orgbuf.length() > 0) cc->setOrganization(orgbuf.str()); if(oubuf.length() > 0) cc->setOrganizationalUnit(oubuf.str()); if(ebuf.length() > 0) cc->setEmail(ebuf.str()); if(cnbuf.length() > 0) cc->setDestAddr(cnbuf.str()); if(action == CSR) { if(pbuf.length() > 0) cc->setPassphrase(pbuf.str()); else throw MakeStringException(-1, "passphrase not specified."); StringBuffer csrbuf, privkey; if(pfbuf.length() == 0) { cc->generateCSR(privkey, csrbuf); if(opfio.get() != NULL) opfio->write(0, privkey.length(), privkey.str()); else printf("\n%s\n", privkey.str()); if(orfio.get() != NULL) orfio->write(0, csrbuf.length(), csrbuf.str()); else printf("\n%s\n", csrbuf.str()); } else { privkey.loadFile(pfbuf.str()); cc->generateCSR(privkey.str(), csrbuf); if(orfio.get() != NULL) orfio->write(0, csrbuf.length(), csrbuf.str()); else printf("\n%s\n", csrbuf.str()); } } else if(action == CRT) { if(daysbuf.length() > 0) { cc->setDays(atoi(daysbuf.str())); } if(pbuf.length() > 0) cc->setPassphrase(pbuf.str()); else throw MakeStringException(-1, "passphrase not specified."); StringBuffer certbuf, privkey; if(pfbuf.length() == 0) { cc->generate(certbuf, privkey); if(opfio.get() != NULL) opfio->write(0, privkey.length(), privkey.str()); else printf("\n%s\n", privkey.str()); if(ocfio.get() != NULL) ocfio->write(0, certbuf.length(), certbuf.str()); else printf("\n%s\n", certbuf.str()); } else { privkey.loadFile(pfbuf.str()); cc->generate(certbuf, privkey.str()); if(ocfio.get() != NULL) ocfio->write(0, certbuf.length(), certbuf.str()); else printf("\n%s\n\n", certbuf.str()); } } } else if(stricmp(argv[1], "-sign") == 0) { StringBuffer csrbuf, ca_cert, ca_privkey, certbuf; if(rfbuf.length() == 0 || cfbuf.length() == 0 || pfbuf.length() == 0) throw MakeStringException(-1, "You need to specify csr file, certificate file and privatekey file"); csrbuf.loadFile(rfbuf.str()); ca_cert.loadFile(cfbuf.str()); ca_privkey.loadFile(pfbuf.str()); if(pbuf.length() == 0) throw MakeStringException(-1, "passphrase not specified."); int days = 365; if(daysbuf.length() > 0) { days = atoi(daysbuf.str()); } signCertificate(csrbuf.str(),ca_cert.str(), ca_privkey.str(), pbuf.str(), days, certbuf); if(ocfio.get() != NULL) ocfio->write(0, certbuf.length(), certbuf.str()); else printf("\n%s\n", certbuf.str()); } else { usage(); return -1; } } catch(IException* e) { StringBuffer errmsg; printf("\nError - %s\n", e->errorMessage(errmsg).str()); e->Release(); } catch(...) { printf("\nUnknown error."); } releaseAtoms(); return 0; }
// ----------- ReadTraits ------------- traits ReadTraits(char traitfile[50]) { struct traits C; FILE *Cread; char line[MAXTRAITLINE]; int i, j, waitingforspace; int nline, words; int extra = 0; char word[(int) (MAXTRAITLINE / 2)][(int) (MAXTRAITLINE / 2)]; char tmp[MAXTAXONLENGTH + 6]; int lineending; C.ntaxa = 0; C.ntraits = 0; // pre-pre-read lineending = whatnewline(traitfile); // preread: if ((Cread = fopen(traitfile, "r")) == NULL) { printf("Cannot open traits file\n"); exit(0); } nline = 0; words= 0; while (myfgets(line, 1000, Cread, lineending) != NULL) { // parse the first line // should be able to do this with iterative scanf, but I couldn't // work it out - this is clunky! if (nline < 2) { waitingforspace = 1; strcpy(word[0], ""); words= 0; for (i = 0; i < strlen(line); i++) { if (isspace(line[i]) && (waitingforspace)) { words++; strcpy(word[words], ""); waitingforspace = 0; } else if (isspace(line[i])) // 2nd+ space in a series of white { } else { strncat(word[words] , &line[i], 1); waitingforspace = 1; } } if(nline==1) { // to see if there is a names line if (strcmp(word[0], "name") ==0) extra = 1; } } nline++; } fclose(Cread); C.ntraits = words-1; C.type = ivector(0, C.ntraits-1); C.ntaxa = nline -1 -extra; C.taxon = cmatrix(0 , C.ntaxa-1, 0 , MAXTAXONLENGTH); C.tr = matrix(0, C.ntaxa-1, 0, C.ntraits-1); C.trname = cmatrix(0, C.ntraits-1, 0, MAXTAXONLENGTH); strcpy(C.trname[0], "nonames"); // printf("traits: %d\ttaxa: %d\n", C.ntraits, C.ntaxa); // real read Cread = fopen(traitfile, "r"); nline = 0; while (myfgets(line, 1000, Cread, lineending) != NULL) { words= 0; strcpy(word[0], ""); waitingforspace = 1; // parse into words, every line for (i = 0; i < strlen(line); i++) { if (isspace(line[i]) && (waitingforspace)) { words++; strcpy(word[words], ""); waitingforspace = 0; } else if (isspace(line[i])) { } else { strncat(word[words] , &line[i], 1); waitingforspace = 1; } } if(nline==0) { // now we know how many traits for (j = 1; j< words; j++) { C.type[j-1] = atoi(word[j]); } } else // lines 2+ { // check (again) for trait names if ((nline == 1) && (extra == 1)) { for (j = 1; j < words; j++) { strcpy(C.trname[j-1], word[j]); } } else // either line 3+ or line 2 with no trait names { // assign taxon name strcpy(C.taxon[(nline-1)-extra], word[0]); for (j = 1; j < words; j++) { C.tr[nline-1-extra][j-1] = (float) atof(word[j]); // printf("%s\t%d\t%f\n", C.taxon[nline-1], j-1, (float) atof(word[j])); } } } nline++; } fclose(Cread); // assign taxon names if there are none if (extra != 1) // if no trait names given { for (j = 0; j < C.ntraits; j++) { sprintf(tmp, "trait_%d", j+1); strcpy(C.trname[j], tmp); } } for (i = 0; i < C.ntraits; i++) { if (C.type[i] == 1) { printf("Char type = 1; multistate characters not implemented yet\n"); exit(EXIT_FAILURE); } } return C; }
// ---------------- ReadSample --------------------------- sample ReadSample(char samplefile[50]) { struct sample InSample; char line[500]; int abundI; char preAbund[50]; int i, j, z, found; char plotname[MAXPLOTLENGTH+1]; char lastplot[MAXPLOTLENGTH+1]; char taxaI[MAXTAXONLENGTH+1]; int lineending; strcpy(lastplot, ""); i = 0; InSample.nrec = 0; InSample.nsamples = 0; InSample.maxrec = 0; InSample.ntaxa = 0; InSample.totabund = 0; // pre-pre-read lineending = whatnewline(samplefile); // preread: // READ PROPERLY if ((Ft = fopen(samplefile, "r")) == NULL) { printf("Cannot open sample file\n"); exit(0); } while (myfgets(line, 500, Ft, lineending) != NULL) // OK to lv length undynamic { sscanf(line, "%s %s %s", plotname, preAbund, taxaI); // string // Test for non-integer abundances: z = 0; while (preAbund[z] != '\0') { // printf("%d %d\n", z, preAbund[z]); if (!isdigit(preAbund[z])) { fprintf(stderr,"Error: sample abundances must be integers\n"); exit(1); } z++; } InSample.nrec++; // if a new plot: if (strcmp(lastplot, plotname) != 0) { InSample.nsamples ++; i = 0; strcpy(lastplot, plotname); } i++; if (InSample.maxrec < i) InSample.maxrec = i; } fclose(Ft); //printf("nrec = %d; nsamples = %d; maxrec = %d\n", InSample.nrec, InSample.nsamples, InSample.maxrec); // Dimension structure InSample.srec = ivector(0, InSample.nsamples - 1); InSample.irec = ivector(0, InSample.nsamples - 1); InSample.id = imatrix(0, InSample.nsamples - 1, 0, InSample.maxrec); InSample.abund = imatrix(0, InSample.nsamples - 1, 0, InSample.maxrec); InSample.pabund = matrix(0, InSample.nsamples - 1, 0, InSample.maxrec); InSample.taxa = cmatrix(0, InSample.nrec-1, 0, MAXTAXONLENGTH); InSample.pname = cmatrix(0, InSample.nsamples - 1, 0, MAXPLOTLENGTH); // Read file for dynamic structure strcpy(lastplot, ""); i = 0; InSample.nsamples = 0; // recycling as counter Ft = fopen(SampleFile, "r"); while (myfgets(line, 500, Ft, lineending) != NULL) { sscanf(line, "%s %d %s", plotname, &abundI, taxaI); // do this on the first line of each new plot if (strcmp(lastplot, plotname) != 0) { strcpy(InSample.pname[InSample.nsamples], plotname); InSample.nsamples ++; i = 0; strcpy(lastplot, plotname); InSample.srec[InSample.nsamples-1]=0; } // recs per sample counter InSample.srec[InSample.nsamples-1]++; // set abundance InSample.abund[InSample.nsamples-1][i] = abundI; // set taxon // all other cases than first found = 0; for (j = 0; j < InSample.ntaxa; j++) { if (strcmp(InSample.taxa[j], taxaI) == 0) { InSample.id[InSample.nsamples-1][i] = j; found = 1; break; } } // new taxon found - executed on first line if(found == 0) { strcpy(InSample.taxa[InSample.ntaxa], taxaI); InSample.id[InSample.nsamples-1][i] = InSample.ntaxa; InSample.ntaxa++; } i++; } fclose(Ft); //Calculate sample and species total abundances and frequency InSample.sppabund = lvector(0, InSample.ntaxa - 1); InSample.psppabund = vector(0, InSample.ntaxa -1 ); InSample.sppfreq = lvector(0, InSample.ntaxa - 1); InSample.psppfreq = vector(0, InSample.ntaxa -1 ); // clear by sample, insample for (i = 0; i < InSample.nsamples; i++) { InSample.irec[i] = 0; for (j = 0; j < InSample.srec[i];j++) { InSample.irec[i] += InSample.abund[i][j]; InSample.sppabund[InSample.id[i][j]] = 0; } } // clear by taxonNo in all samples for (i = 0; i < InSample.ntaxa; i++) { InSample.sppfreq[i] = 0; } // calculate for (i = 0; i < InSample.nsamples; i++) { for (j = 0; j < InSample.srec[i];j++) { InSample.pabund[i][j] = (float) InSample.abund[i][j] / (float) InSample.irec[i]; InSample.sppabund[InSample.id[i][j]] += InSample.abund[i][j]; InSample.totabund += InSample.abund[i][j]; InSample.sppfreq[InSample.id[i][j]]++; // printf("%d %d %d %s %d\n", i, j, InSample.id[i][j], InSample.taxa[InSample.id[i][j]], (int) InSample.sppabund[InSample.id[i][j]]); } } for (i = 0; i < InSample.ntaxa; i++) { InSample.psppabund[i] = (float) InSample.sppabund[i] / (float) InSample.totabund; InSample.psppfreq[i] = (float) InSample.sppfreq[i] / (float) InSample.nsamples; } return InSample; }
void Bladj(phylo Intree) { int i, j, q, z, l = 0; int *action; int *AgeFixed; char nameI[50]; float ageI; int matched; char line[201]; // array of characters from input line int lineending; // Dimension things: action = ivector(0, Intree.nnodes -1); AgeFixed = ivector(0, Intree.nnodes -1); // Fix ages for nodes of terminal taxa in Phylogeny: for (i = 0; i < Intree.nnodes; i++) { // terminal nodes if (Intree.noat[i] == 0) { Intree.age[i] = 0.0; AgeFixed[i] = 1; } else { Intree.age[i] = 99999.9; AgeFixed[i] = 0; } } // pre-read lineending = whatnewline(INFILEA); //Fix node ages for nodes found in ages file Fa = fopen(INFILEA, "r"); while (myfgets(line, 200, Fa, lineending) != NULL) { sscanf(line, "%s %f", nameI, &ageI); // string matched = 0; for (z = 0; z < Intree.nnodes; z++) { if (strcmp(Intree.taxon[z], nameI) == 0) { Intree.age[z] = ageI; AgeFixed[z] = 1; matched = 1; } } } fclose(Fa); //TODO will crash if no name/age for deepest node, need to add check for this // The algorithm: // 1. create network of fixed age nodes between the root and the other // fixed age nodes, choosing the order of nodes to operate on first // using age, then number of intervening nodes. for (i = 0; i < Intree.nnodes; i++) { q = 0; for (j = i+1; j < Intree.nnodes; j++) { // find all the line-of-site ages action[q] = 0; // correct for errors in ages if ((LineOfSight(Intree, AgeFixed, i, j) == 1) && \ (Intree.age[j] >= Intree.age[i])) AgeFixed[j] = 0; if ((AgeFixed[j] == 1) && (LineOfSight(Intree, AgeFixed, i, j) == 1)) { // printf("%d+%d ",i, j); action[q] = j; q++; } } // Now sort the action SortAction(Intree, action, q, i); // Adjust lengths for (l = 0; l < q; l++) { Adjust(Intree, AgeFixed, i, action[l]); //printf("i%d action%d\n",i, action[l]); } } if (FYOUT) FyOut(Intree) ; else Fy2newRec(Intree); }
int main(int argc, char **argv) { FILE *fp,*fw; char s[1024]; u_char chbuf[MAX_PHRASE_LEN * CH_SZ]; u_short phbuf[80]; u_int phbuf32[80]; u_int64_t phbuf64[80]; int i,j,idx,len, ofs; u_short kk; u_int64_t kk64; int hashidx[TSIN_HASH_N]; u_char clen; int lineCnt=0; gboolean reload = getenv("HIME_NO_RELOAD")==NULL; if (reload) { dbg("need reload\n"); } else { dbg("NO_GTK_INIT\n"); } if (getenv("NO_GTK_INIT")==NULL) gtk_init(&argc, &argv); dbg("enter %s\n", argv[0]); if (argc < 2) p_err("must specify input file"); init_TableDir(); if ((fp=fopen(argv[1], "rb"))==NULL) { printf("Cannot open %s\n", argv[1]); exit(-1); } skip_utf8_sigature(fp); char *outfile; int fofs = ftell(fp); myfgets(s, sizeof(s), fp); if (strstr(s, "!!pinyin")) { b_pinyin = TRUE; printf("is pinyin\n"); load_pin_juyin(); } else fseek(fp, fofs, SEEK_SET); fofs = ftell(fp); int keybits=0, maxkey=0; char keymap[128]; char kno[128]; bzero(kno, sizeof(kno)); myfgets(s, sizeof(s), fp); puts(s); if (strstr(s, TSIN_GTAB_KEY)) { is_gtab = TRUE; lineCnt++; if (argc < 3) p_err("useage %s input_file output_file", argv[0]); outfile = argv[2]; len=strlen((char *)s); if (s[len-1]=='\n') s[--len]=0; char aa[128]; keymap[0]=' '; sscanf(s, "%s %d %d %s", aa, &keybits, &maxkey, keymap+1); for(i=0; keymap[i]; i++) kno[keymap[i]]=i; if (maxkey * keybits > 32) gtabkey64 = TRUE; } else { if (argc==3) outfile = argv[2]; else outfile = "tsin32"; fseek(fp, fofs, SEEK_SET); } INMD inmd, *cur_inmd = &inmd; char *cphbuf; if (is_gtab) { cur_inmd->keybits = keybits; if (gtabkey64) { cphbuf = (char *)phbuf64; phsz = 8; key_cmp = key_cmp64; hash_shift = TSIN_HASH_SHIFT_64; cur_inmd->key64 = TRUE; } else { cphbuf = (char *)phbuf32; phsz = 4; hash_shift = TSIN_HASH_SHIFT_32; key_cmp = key_cmp32; cur_inmd->key64 = FALSE; } cur_inmd->last_k_bitn = (((cur_inmd->key64 ? 64:32) / cur_inmd->keybits) - 1) * cur_inmd->keybits; dbg("cur_inmd->last_k_bitn %d\n", cur_inmd->last_k_bitn); } else { cphbuf = (char *)phbuf; phsz = 2; key_cmp = key_cmp16; hash_shift = TSIN_HASH_SHIFT; } dbg("phsz: %d\n", phsz); phcount=ofs=0; while (!feof(fp)) { usecount_t usecount=0; lineCnt++; myfgets((char *)s,sizeof(s),fp); len=strlen((char *)s); if (s[0]=='#') continue; if (strstr(s, TSIN_GTAB_KEY)) continue; if (s[len-1]=='\n') s[--len]=0; if (len==0) continue; i=0; int chbufN=0; int charN = 0; while (s[i]!=' ' && i<len) { int len = utf8_sz((char *)&s[i]); memcpy(&chbuf[chbufN], &s[i], len); i+=len; chbufN+=len; charN++; } while ((i < len && s[i]==' ') || s[i]=='\t') i++; int phbufN=0; while (i<len && phbufN < charN && s[i]!=' ') { if (is_gtab) { kk64=0; int idx=0; while (s[i]!=' ' && i<len) { int k = kno[s[i]]; kk64|=(u_int64_t)k << ( LAST_K_bitN - idx*keybits); i++; idx++; } if (phsz==8) phbuf64[phbufN++]=kk64; else phbuf32[phbufN++]=(u_int)kk64; } else { kk=0; if (b_pinyin) { kk = pinyin2phokey(s+i); while (s[i]!=' ' && i<len) i++; } else { while (s[i]!=' ' && i<len) { if (kk==(BACK_QUOTE_NO << 9)) kk|=s[i]; else kk |= lookup((u_char *)&s[i]); i+=utf8_sz((char *)&s[i]); } } phbuf[phbufN++]=kk; } i++; } if (phbufN!=charN) { p_err("%s Line %d problem in phbufN!=chbufN %d != %d\n", s, lineCnt, phbufN, chbufN); } clen=phbufN; while (i<len && s[i]==' ') i++; if (i==len) usecount = 0; else usecount = atoi((char *)&s[i]); /* printf("len:%d\n", clen); */ if (phcount >= phidxsize) { phidxsize+=1024; if (!(phidx=(int *)realloc(phidx,phidxsize*4))) { puts("realloc err"); exit(1); } } phidx[phcount++]=ofs; int new_bfN = ofs + 1 + sizeof(usecount_t)+ phsz * clen + chbufN; if (bfsize < new_bfN) { bfsize = new_bfN + 1024*1024; bf = (char *)realloc(bf, bfsize); } memcpy(&bf[ofs++],&clen,1); memcpy(&bf[ofs],&usecount, sizeof(usecount_t)); ofs+=sizeof(usecount_t); memcpy(&bf[ofs], cphbuf, clen * phsz); ofs+=clen * phsz; memcpy(&bf[ofs], chbuf, chbufN); ofs+=chbufN; } fclose(fp); /* dumpbf(bf,phidx); */ puts("Sorting ...."); qsort(phidx,phcount, sizeof(phidx[0]),qcmp); if (!(sf=(u_char *)malloc(bfsize))) { puts("malloc err"); exit(1); } if (!(sidx=(int *)malloc(phidxsize*sizeof(int)))) { puts("malloc err"); exit(1); } // delete duplicate ofs=0; j=0; for(i=0;i<phcount;i++) { idx = phidx[i]; sidx[j]=ofs; len=bf[idx]; int tlen = utf8_tlen(&bf[idx + 1 + sizeof(usecount_t) + phsz*len], len); clen= phsz*len + tlen + 1 + sizeof(usecount_t); if (i && !qcmp_eq(&phidx[i-1], &phidx[i])) continue; memcpy(&sf[ofs], &bf[idx], clen); j++; ofs+=clen; } phcount=j; #if 1 puts("Sorting by usecount ...."); qsort(sidx, phcount, 4, qcmp_usecount); #endif for(i=0;i<256;i++) hashidx[i]=-1; for(i=0;i<phcount;i++) { idx=sidx[i]; idx+= 1 + sizeof(usecount_t); int v; if (phsz==2) { phokey_t kk; memcpy(&kk, &sf[idx], phsz); v = kk >> TSIN_HASH_SHIFT; } else if (phsz==4) {
int main(int argc, char **argv) { typedef struct structinfo { char name[1023]; /* Server hostname */ int hits; /* Number of requests to that server */ long bytes; /* Total bytes from that server */ FILE *details; /* Where to write details about each request */ struct structinfo *next; /* Pointer to info about next host */ } hostinfo; const char roothtml[] = "index.html"; const char txtext[] = ".txt"; const char htmlhead1[] = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<HTML lang=\"en\" dir=\"LTR\">\n<HEAD>\n<META name=\"description\" lang=\"en\" content=\"\">\n<META content=\"text/html; charset=iso-8859-1\" http-equiv=Content-Type>\n<TITLE>"; const char htmlhead2[] = "</TITLE>\n</HEAD>\n<BODY>\n"; const char htmlfoot[] = "</BODY>\n</HTML>\n"; FILE *infile = NULL, *outfile = NULL; char ipaddress[17] = ""; /* IP address to spy */ char logname[255] = "access.log"; /* Logfile */ char dirname[255] = ""; /* Directory for generated files */ struct { char line[1023]; /* Whole line */ char url[1023]; /* Whole name of object requested */ char hostname[1023]; /* Pure hostname requested */ } log; /* Data extracted from one line of logfile */ struct { char userlog, userdir, verbose; } options = {0, 0, 0}; /* Options given as arguments */ char dead = 0; /* How and why it ended */ hostinfo *acthost = NULL, *firsthost = NULL, *tmphost = NULL; int hostcount = 0, totalhits = 0; long bytescount = 0; char *a, *b; int c, d, e; char f[255]; long g; for (c = 1; c < argc; c++) if (argv[c][0] != '-') { /* Argument is probably a file/directory/IP */ if (options.userlog) { strncpy(logname, argv[c], 255); options.userlog = 0; } /* if */ else if (options.userdir) { strncpy(dirname, argv[c], 255); options.userdir = 0; } /* else if */ else strncpy(ipaddress, argv[c], 15); } /* if */ else { /* Argument is a switch */ options.userlog = 0; options.userdir = 0; switch (argv[c][1]) { case 'l': options.userlog = 1; break; case 'd': options.userdir = 1; break; case 'v': options.verbose = 1; break; case 'h': default: dead = 5; } /* switch */ } /* else */ if ((d = strlen(ipaddress)) == 0) dead = 5; else { if ((c = strlen(dirname)) == 0) strncpy(dirname, ipaddress, 16); strncat(dirname, "/", 1); if (d > 15) d = 15; for (c = (d - 1); c >= 0; c--) ipaddress[c + 1] = ipaddress[c]; ipaddress[0] = ' '; ipaddress[d + 1] = ' '; ipaddress[d + 2] = '\0'; } /* else */ if ((options.verbose != 0) || (dead == 5)) { printf(" Who&Where v0.1.4 \n"); printf(" Statistic generator for Oops log files \n\n"); } if (options.verbose != 0) { printf("IP address: %s\n", ipaddress); printf("Logfile: %s\n", logname); printf("Work directory: %s\n", dirname); } /* if */ if (dead == 5) ; else if ((infile = fopen(logname, "rt")) == NULL) dead = 1; else { mkdir(dirname, 493); chdir(dirname); while (((c = myfgets(infile, log.line, 1023)) != EOF) && (dead == 0)) if ((a = strstr(log.line, ipaddress)) != 0) { if (options.verbose != 0) printf("Hosts: %d Hits: %d Bytes: %d\r", hostcount, totalhits, bytescount); totalhits++; a = skipchars(log.line, ' ', 4); b = f; while (((*b++ = *a++) != ' ') && (*a != '\0')) ; *b = '\0'; g = atol(f); bytescount += g; a = skipchars(log.line, ' ', 6); b = log.url; while (((*b++ = *a++) != ' ') && (*a != '\0') && (*a != '%')) ; *b++ = '\n'; *b = '\0'; a = skipchars(log.url, '/', 2); b = log.hostname; while (((*b++ = *a++) != '/') && (*a != '\0')) ; b--; *b = '\0'; acthost = firsthost; for (c = 1; c <= hostcount; c++) { if ((d = strcmp(acthost->name, log.hostname)) == 0) { acthost->hits += 1; acthost->bytes += g; if ((d = fprintf(acthost->details, log.url)) == EOF) dead = 31; c = hostcount + 2; } /* if */ acthost = acthost->next; } /* for */ if (c == (hostcount + 1)) { if ((tmphost = malloc(sizeof(hostinfo))) == NULL) dead = 4; else { if (hostcount > 0) acthost->next = tmphost; else firsthost = tmphost; acthost = tmphost; acthost->next = tmphost; strncpy(acthost->name, log.hostname, 1023); acthost->hits = 1; acthost->bytes = g; hostcount += 1; strncpy(f, acthost->name, 251); strncat(f, txtext, 4); if ((acthost->details = fopen(f, "w+t")) == NULL) dead = 3; else if ((d = fprintf(acthost->details, log.url)) == EOF) dead = 31; } /* else */ } /* if */ } /* if */ } /* else */ if ((dead != 1) && (dead != 5)) { if ((outfile = fopen(roothtml, "w+t")) == NULL) dead = 2; else if ((d = fprintf(outfile, htmlhead1)) == EOF) dead = 21; else if ((d = fprintf(outfile, ipaddress)) == EOF) dead = 21; else if ((d = fprintf(outfile, htmlhead2)) == EOF) dead = 21; else if ((d = fprintf(outfile, "<H1><U>Proxy request statistic for%s</U></H1>\n<P>\n<B>Hosts requested:</B> %d<BR>\n<B>Total requests:</B> %d<BR>\n<B>Total bytes:</B> %d<BR>\n</P>\n", ipaddress, hostcount, totalhits, bytescount)) == EOF) dead = 21; for (e = 1; e <= hostcount; e++) { acthost = firsthost; tmphost = firsthost; while (tmphost->details == NULL) tmphost = tmphost->next; for (c = 1; c <= hostcount; c++) { if ((acthost->hits > tmphost->hits) && (acthost->details != NULL)) tmphost = acthost; acthost = acthost->next; } /* for */ if ((d = fprintf(outfile, "<P><B>%s</B> (%d <A HREF=\"%s%s\">hit(s)</A>/%d bytes)</P>\n", tmphost->name, tmphost->hits, tmphost->name, txtext, tmphost->bytes)) == EOF) dead = 21; fclose(tmphost->details); tmphost->details = NULL; } /* for */ if ((d = fprintf(outfile, htmlfoot)) == EOF) dead = 21; acthost = firsthost; for (c = 1; c <= hostcount; c++) if (acthost == NULL) c = hostcount + 1; else { tmphost = acthost; acthost = acthost->next; free(tmphost); } /* else */ if (outfile != NULL) fclose(outfile); } /* if */ if (infile != NULL) fclose(infile); switch (dead) { case 0: if (options.verbose != 0) printf("\nDone. See '%sindex.html' for results.\n\n", dirname); break; case 1: printf("\nError opening input file.\n\n"); break; case 2: printf("\nError opening output file.\n\n"); break; case 3: printf("\nError opening details output file.\n\n"); break; case 21: printf("\nError writing output file.\n\n"); break; case 31: printf("\nError writing details output file.\n\n"); break; case 4: printf("\nError allocating memory.\n\n"); break; case 5: printf("Usage: waw IP_address [-l logfile_name] [-d work_directory] [-v] [-h]\n\n"); printf("-l specify Oops log file, default is ./access.log\n"); printf("-d specify directory to save results, default is same as given IP address\n"); printf("-v be verbose\n"); printf("-h print this help\n\n"); } /* switch */ return 0; } /* main */
int main() { char line[8192]; char* dat; char* timestamp; #ifdef oldandslow setvbuf(stdout,printfbuf,_IOFBF,sizeof printfbuf); while (fgets(line,sizeof(line),stdin)) { int tslen; /* chomp */ { int i; for (i=0; i<sizeof(line) && line[i]; ++i) if (line[i]=='\n') break; line[i]=0; } #else buffer_init(buffer_1,write,1,printfbuf,sizeof printfbuf); while (myfgets(line,sizeof(line))+1>1) { int tslen; #endif /* find out what kind of time stamp there is */ tslen=0; if (line[0]=='@') { /* multilog timestamp */ char* x=strchr(line,' '); if (x) { tslen=x-line; if (tslen!=25) tslen=0; } } else if (isdigit(line[0])) { char* x=strchr(line,' '); if (x && x==line+10) { x=strchr(x+1,' '); if (x && x==line+29) tslen=29; } } if (tslen) { dat=line+tslen+1; line[tslen]=0; timestamp=line; } else { dat=line; timestamp=""; } /* element two is the unique key */ { char* fields[21]; char* x=dat; int i; /* early-out skip the field splitting if we are not interested in * the line anyway */ if (*x != 'a' && *x != 'c' && *x != 'G' && *x != 'P' && *x != 'H') continue; /* split into fields */ for (i=0; i<20; ++i) { char* y=strchr(x,' '); if (!y) break; *y=0; fields[i]=x; x=y+1; } fields[i]=x; ++i; if (!strcmp(fields[0],"accept")) { struct node** N; struct node* x; if (i<2) continue; N=lookup(fields[1]); if (!(x=*N)) { *N=malloc(sizeof(**N)); (*N)->next=0; x=*N; } else { free(x->word); #ifdef oldandslow free(x->ip); free(x->port); free(x->timestamp); #endif } #ifndef oldandslow /* reduce allocations */ x->word=allocassert(malloc((fields[4]-fields[1])+(fields[0]-line))); memcpy(x->word,fields[1],fields[4]-fields[1]); x->ip=x->word+(fields[2]-fields[1]); x->port=x->ip+(fields[3]-fields[2]); x->timestamp=x->port+(fields[4]-fields[3]); memcpy(x->timestamp,line,fields[0]-line); #else x->word=allocassert(strdup(fields[1])); x->ip=allocassert(strdup(fields[2])); x->port=allocassert(strdup(fields[3])); x->timestamp=allocassert(strdup(line)); #endif } else if (!strncmp(fields[0],"close/",6)) { struct node** N; N=lookup(fields[1]); if (*N) { struct node* y=(*N)->next; struct node* x=*N; free(x->word); #ifdef oldandslow free(x->ip); free(x->port); free(x->timestamp); #endif free(x); *N=y; } } else if (cmp3(fields[0],"GET") || cmp4(fields[0],"POST") || cmp4(fields[0],"HEAD")) { if (i>6) { /* otherwise it's a format violation and we ignore the line */ struct node** N; N=lookup(fields[1]); #ifdef oldandslow printf("%s %s %s http%s://%s%s %s %s %s\n", timestamp,fields[0],*N?(*N)->ip:"::", strstr(fields[0],"SSL")?"s":"",fields[6],fields[2],fields[3],fields[4],fields[5]); #else buffer_putm(buffer_1,timestamp," ",fields[0]," ",*N?(*N)->ip:"::"," http", strstr(fields[0],"SSL")?"s":"","://",fields[6],fields[2]," ", fields[3]," ",fields[4]," ",fields[5],"\n"); #endif } } } } #ifndef oldandslow buffer_flush(buffer_1); #endif return 0; }
static gboolean read_syms() { FILE *fp; static char symbol_table[] = "symbol-table"; static time_t file_modify_time; if ((fp=watch_fopen(symbol_table, &file_modify_time))==NULL) return FALSE; skip_utf8_sigature(fp); int pg; for(pg=0; pg < pagesN; pg++) { syms = pages[pg].syms; symsN = pages[pg].symsN; int i; for(i=0; i < symsN; i++) { int j; for(j=0; j < syms[i].symN; j++) if (syms[i].sym[j]) free(syms[i].sym[j]); } free(syms); } pagesN = 0; pages = NULL; syms = NULL; symsN = 0; while (!feof(fp)) { char tt[1024]; bzero(tt, sizeof(tt)); myfgets(tt, sizeof(tt), fp); // dbg("%d] %s\n",strlen(tt), tt); int len=strlen(tt); #if 0 if (!len) continue; if (tt[len-1]=='\n') { tt[len-1]=0; } #endif if (tt[0]==0) save_page(); if (tt[0]=='#') continue; char *p=tt; syms=trealloc(syms, SYM_ROW, symsN+1); SYM_ROW *psym = &syms[symsN++]; bzero(psym, sizeof(SYM_ROW)); while (*p) { char *n = p; while (*n && *n!='\t') n++; *n = 0; psym->sym=trealloc(psym->sym, char *, psym->symN+1); psym->sym[psym->symN++] = strdup(p); p = n + 1; } if (!psym->symN) { free(syms); syms=NULL; symsN=0; } } if (symsN) save_page(); fclose(fp); idx = 0; syms = pages[idx].syms; symsN = pages[idx].symsN; return TRUE; }
int main(void) { char command; char buffer[128]; int key, data; int* p; int i; do { puts( "コマンドを入力して下さい" ); puts( "データを格納:a" ); puts( "データを探索:b" ); puts( "データをクリア:c" ); puts( "終了:q" ); myfgets(buffer, 2); sscanf(buffer, "%c", &command); switch( command ) { case 'a': /* データを格納 */ puts( "キーを入力して下さい" ); myfgets(buffer, 4); sscanf(buffer, "%d", &key); puts( "データを入力して下さい" ); myfgets(buffer, 100); sscanf(buffer, "%d", &data); i = add( key, data ); switch( i ) { case 0: puts( "はじめての作成" ); break; case 1: puts( "チェイン作成" ); break; default: puts( "error" ); break; } break; case 'b': /* データを探索 */ puts( "キーを入力して下さい" ); myfgets(buffer, 4); sscanf(buffer, "%d", &key); p = search( key ); if( p != NULL ) { printf( "キー%dに対応するのは%d\n", key, *p ); } else { printf( "キー%dに対応するデータはありません\n", key ); } break; case 'c': /* クリア */ clear(); break; case 'q': break; default: puts( "コマンドが正しくありません" ); break; } printf( "\n\n" ); } while( command != 'q' ); /* ハッシュ表をクリア */ clear(); return 0; }
int main(int argc, char **argv) { char *fname = "pho.tab2.src"; FILE *fp; char s[64]; int phrase_area_N=0; char *phrase_area = NULL; if (!getenv("NO_GTK_INIT")) gtk_init(&argc, &argv); if (argc > 1) fname = argv[1]; if ((fp=fopen(fname,"rb"))==NULL) p_err("cannot open %s\n", fname); while (!feof(fp)) { s[0]=0; myfgets(s,sizeof(s),fp); int len=strlen(s); if (s[len-1]=='\n') s[--len]=0; if (len==0) continue; phokey_t kk=0; char *p = s; while (*p && *p!=' ' && *p!=9) { if (kk==(BACK_QUOTE_NO << 9)) kk|=*p; else kk |= lookup((u_char *)p); p += utf8_sz(p); } items[itemsN].key = kk; p++; char *str = p; while (*p && *p != ' ' && *p!=9) p++; *p = 0; p++; int slen = strlen(str); if (slen==utf8_sz(str)) { u8cpy((char *)items[itemsN].ch, str); } else { dbg("str %s\n", str); int newN = phrase_area_N + slen + 1; phrase_area = trealloc(phrase_area, char, newN); strcpy(phrase_area + phrase_area_N, str); items[itemsN].ch[0] = PHO_PHRASE_ESCAPE; items[itemsN].ch[1] = phrase_area_N & 0xff; items[itemsN].ch[2] = (phrase_area_N>>8) & 0xff; items[itemsN].ch[3] = (phrase_area_N>>16) & 0xff; phrase_area_N = newN; } items[itemsN].count = atoi(p); items[itemsN].oseq = itemsN; itemsN++; } fclose(fp); qsort(items, itemsN, sizeof(PHITEM), qcmp_key_del); int i; #if 1 int newN = 1; for(i=1;i<itemsN;i++) if (qcmp_key_del(&items[i-1], &items[i])) items[newN++] = items[i]; else { #if 0 prph(items[i].key); utf8_putchar((char *)items[i].ch); dbg("\n"); #endif } if (itemsN != newN) { dbg("deleted %d %d\n",itemsN, newN); itemsN = newN; } #endif qsort(items, itemsN, sizeof(PHITEM), qcmp_key); PHO_IDX pho_idx[3000]; u_short pho_idxN=0; for(i=0; i < itemsN; ) { phokey_t key = items[i].key; pho_idx[pho_idxN].key = key; pho_idx[pho_idxN].start = i; pho_idxN++; int j; for (j=i+1; j < itemsN && items[j].key == key; j++); int l; for(l=i; l<j; l++) { bchcpy(pho_items[pho_itemsN].ch, items[l].ch); pho_items[pho_itemsN].count = items[l].count; pho_itemsN++; } i = j; } char *tp = strstr(fname, ".tab2.src"); if (!tp) p_err("file name should be *.tab2.src"); tp = strstr(fname, ".src"); *tp=0; char *fname_out = fname; if ((fp=fopen(fname_out,"wb"))==NULL) p_err("cannot create %s\n", fname_out); fwrite("PH",1,2,fp); // dbg("pho_itemsN:%d pho_idxN:%d\n", pho_itemsN, pho_idxN); fwrite(&pho_idxN, sizeof(u_short), 1, fp); fwrite(&pho_itemsN, sizeof(pho_itemsN), 1, fp); fwrite(&phrase_area_N, sizeof(phrase_area_N), 1, fp); #if 0 fclose(fp); exit(0); #endif fwrite(pho_idx, sizeof(PHO_IDX), pho_idxN, fp); fwrite(pho_items, sizeof(PHO_ITEM), pho_itemsN, fp); fwrite(phrase_area, 1, phrase_area_N, fp); fclose(fp); if (getenv("HIME_NO_RELOAD")==NULL) { /* caleb- does found where "reload" is used. * caleb- think the send_hime_message() here does nothing. */ send_hime_message(GDK_DISPLAY(), "reload"); } return 0; }
int main(){ char *p, *p2, *p3, *p4, *p5, *p6; p = my_malloc(30); { char i; int j; for(i='a',j=0;i<='z';i++,j++){ p[j] = i; } } p[26] = '\0'; p2 = my_malloc(30); { char i; int j; for(i='a',j=0;i<='z';i++,j++){ p2[j] = i; } } p2[26] = '\0'; printf("%s\n%s\n",p,p2); my_free(p); my_free(p2); heap_report(); p = my_malloc(30); { char i; int j; for(i='a',j=0;i<='z';i++,j++){ p[j] = i; } } p[26] = '\0'; p2 = my_malloc(30); { char i; int j; for(i='a',j=0;i<='z';i++,j++){ p2[j] = i; } } p2[26] = '\0'; printf("%s\n%s\n",p,p2); p3 = my_malloc(1024); p4 = my_malloc(3); p5 = my_malloc(2000); p6 = my_malloc(3); p4 = my_realloc(p4,232); p5 = my_realloc(p5,3); my_free(p); my_free(p2); p3 = my_realloc(p3,11); p4 = my_realloc(p4,342); p5 = my_realloc(p5,321); p6 = my_realloc(p6,233); p4 = my_realloc(p4,12); p3 = my_realloc(p3,11); p4 = my_realloc(p4,23); p3 = my_realloc(p3,232); p4 = my_realloc(p4,68); p3 = my_realloc(p3,1025); p3 = my_realloc(p3,231); p4 = my_realloc(p4,145); if(!p3 || !p4 || !p5 || !p6 ){ printf("malloc error\n"); return 0; } my_free(p3); my_free(p4); my_free(p5); my_free(p6); heap_report(); while((p = myfgets(stdin)) != NULL){ p2 = myfgets(stdin); printf("%s\n%s\n",p,p2); heap_report(); my_free(p); my_free(p2); heap_report(); } return 0; }
//--------------------------------------------------------------------------- void Calc() { mecChar_t szLine[100]; mecFloat_t fVal = 0, afVarVal[] = { 1, 2, 7.2f, -2.1f }; // Values of the parser variables mecParserHandle_t hParser; mecEvalFun_t pFunEval = NULL; hParser = mecCreate(); // initialize the parser Intro(hParser); // Set an error handler [optional] // the only function that does not take a parser instance handle mecSetErrorHandler(hParser, OnError); //#define GERMAN_LOCALS #ifdef GERMAN_LOCALS mecSetArgSep(hParser, ';'); mecSetDecSep(hParser, ','); mecSetThousandsSep(hParser, '.'); #else mecSetArgSep(hParser, ','); mecSetDecSep(hParser, '.'); #endif // Define parser variables and bind them to C++ variables [optional] mecDefineConst(hParser, _T("const1"), 1); mecDefineConst(hParser, _T("const2"), 2); // Define parser variables and bind them to C++ variables [optional] mecDefineVar(hParser, _T("a"), &afVarVal[0]); mecDefineVar(hParser, _T("b"), &afVarVal[1]); mecDefineVar(hParser, _T("c"), &afVarVal[2]); mecDefineVar(hParser, _T("d"), &afVarVal[3]); // Define infix operator [optional] mecDefineInfixOprt(hParser, _T("!"), Not, 0); // Define functions [optional] mecDefineFun0(hParser, _T("zero"), ZeroArg, 0); mecDefineFun1(hParser, _T("rnd"), Rnd, 0); // Add an unoptimizeable function mecDefineFun2(hParser, _T("dump"), DebugDump, 0); // Define binary operators [optional] mecDefineOprt(hParser, _T("add"), Add, 0, mecOPRT_ASCT_LEFT, 0); mecDefineOprt(hParser, _T("mul"), Mul, 1, mecOPRT_ASCT_LEFT, 0); #ifdef _DEBUG mecDebugDump(1, 0); #endif while (myfgets(szLine, 99, stdin)) { szLine[mystrlen(szLine) - 1] = 0; // overwrite the newline switch (CheckKeywords(szLine, hParser)) { case 0: break; // no keyword found; parse the line case 1: continue; // A Keyword was found do not parse the line case -1: return; // abort the application } // Set the expression mecSetExpr(hParser, szLine); // Compile the expression and get the pointer to the // just in time compiled eval function pFunEval = mecDbgCompile(hParser, -1); if (pFunEval == NULL) { continue; } // calculate the expression fVal = pFunEval(); /* alternative: fVal = mecEval(hParser); // 1st time parse from string and compile expression fVal = mecEval(hParser); // 2nd time parse from JIT code (handled internally) */ // Without an Error handler function // you must use this for error treatment: //if (mecError(hParser)) //{ // printf("\nError:\n"); // printf("------\n"); // printf("Message: %s\n", mecGetErrorMsg(hParser) ); // printf("Token: %s\n", mecGetErrorToken(hParser) ); // printf("Position: %s\n", mecGetErrorPos(hParser) ); // printf("Errc: %s\n", mecGetErrorCode(hParser) ); // continue; //} if (!mecError(hParser)) { myprintf(_T("%f\n"), fVal); } } // while // finalle free the parser ressources mecRelease(hParser); }