这篇教程C++ strcpy函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中strcpy函数的典型用法代码示例。如果您正苦于以下问题:C++ strcpy函数的具体用法?C++ strcpy怎么用?C++ strcpy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了strcpy函数的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: __gnat_setenvvoid__gnat_setenv (char *name, char *value){#if defined (VMS) struct dsc$descriptor_s name_desc; $DESCRIPTOR (table_desc, "LNM$PROCESS"); char *host_pathspec = value; char *copy_pathspec; int num_dirs_in_pathspec = 1; char *ptr; long status; name_desc.dsc$w_length = strlen (name); name_desc.dsc$b_dtype = DSC$K_DTYPE_T; name_desc.dsc$b_class = DSC$K_CLASS_S; name_desc.dsc$a_pointer = name; /* ??? Danger, not 64bit safe. */ if (*host_pathspec == 0) /* deassign */ { status = LIB$DELETE_LOGICAL (&name_desc, &table_desc); /* no need to check status; if the logical name is not defined, that's fine. */ return; } ptr = host_pathspec; while (*ptr++) if (*ptr == ',') num_dirs_in_pathspec++; { int i, status; /* Alloca is guaranteed to be 32bit. */ ile_s *ile_array = alloca (sizeof (ile_s) * (num_dirs_in_pathspec + 1)); char *copy_pathspec = alloca (strlen (host_pathspec) + 1); char *curr, *next; strcpy (copy_pathspec, host_pathspec); curr = copy_pathspec; for (i = 0; i < num_dirs_in_pathspec; i++) { next = strchr (curr, ','); if (next == 0) next = strchr (curr, 0); *next = 0; ile_array[i].len = strlen (curr); /* Code 2 from lnmdef.h means it's a string. */ ile_array[i].code = 2; ile_array[i].adr = curr; /* retlen_adr is ignored. */ ile_array[i].retlen_adr = 0; curr = next + 1; } /* Terminating item must be zero. */ ile_array[i].len = 0; ile_array[i].code = 0; ile_array[i].adr = 0; ile_array[i].retlen_adr = 0; status = LIB$SET_LOGICAL (&name_desc, 0, &table_desc, 0, ile_array); if ((status & 1) != 1) LIB$SIGNAL (status); }#elif (defined (__vxworks) && defined (__RTP__)) / || defined (__APPLE__) / || defined (__OpenBSD__) setenv (name, value, 1);#else size_t size = strlen (name) + strlen (value) + 2; char *expression; expression = (char *) xmalloc (size * sizeof (char)); sprintf (expression, "%s=%s", name, value); putenv (expression);#if (defined (__FreeBSD__) && (__FreeBSD__ < 7)) / || defined (__MINGW32__) / ||(defined (__vxworks) && ! defined (__RTP__)) /* On some systems like FreeBSD 6.x and earlier, MacOS X and Windows, putenv is making a copy of the expression string so we can free it after the call to putenv */ free (expression);#endif#endif}
开发者ID:jrmarino,项目名称:draco,代码行数:92,
示例2: update_phtableint update_phtable(presentity_t* presentity, str pres_uri, str body){ char* sphere= NULL; unsigned int hash_code; pres_entry_t* p; int ret= 0; str* xcap_doc= NULL; /* get new sphere */ sphere= extract_sphere(body); if(sphere==NULL) { LM_DBG("no sphere defined in new body/n"); return 0; } /* search for record in hash table */ hash_code= core_hash(&pres_uri, NULL, phtable_size); lock_get(&pres_htable[hash_code].lock); p= search_phtable(&pres_uri, presentity->event->evp->parsed, hash_code); if(p== NULL) { lock_release(&pres_htable[hash_code].lock); goto done; } if(p->sphere) { if(strcmp(p->sphere, sphere)!= 0) { /* new sphere definition */ shm_free(p->sphere); } else { /* no change in sphere definition */ lock_release(&pres_htable[hash_code].lock); pkg_free(sphere); return 0; } } p->sphere= (char*)shm_malloc(strlen(sphere)+ 1); if(p->sphere== NULL) { lock_release(&pres_htable[hash_code].lock); ret= -1; goto done; } strcpy(p->sphere, sphere); lock_release(&pres_htable[hash_code].lock); /* call for watchers status update */ if(presentity->event->get_rules_doc(&presentity->user, &presentity->domain, &xcap_doc)< 0) { LM_ERR("failed to retreive xcap document/n"); ret= -1; goto done; } update_watchers_status(pres_uri, presentity->event, xcap_doc);done: if(xcap_doc) { if(xcap_doc->s) pkg_free(xcap_doc->s); pkg_free(xcap_doc); } if(sphere) pkg_free(sphere); return ret;}
开发者ID:Distrotech,项目名称:opensips,代码行数:83,
示例3: mainint main(int argc,char **argv){ int sockfd; char buffer[1024]; struct sockaddr_in server_addr; struct hostent *host; int portnumber,nbytes; char host_addr[256]; char host_file[256]; char local_file[256]; FILE *fp; char request[1024]; int send,totalsend; int i; char *pt; if(argc!=2){ fprintf(stderr,"Usage:%s web-address/a/n",argv[0]); exit (1); } printf("parameter.1 is: %s/n",argv[1]); ToLowerCase(argv[1]); printf("lowercase parameter.1 is: %s/n",argv[1]); GetHost(argv[1],host_addr,host_file,&portnumber); printf("webhost:%s/n",host_addr); printf("hostfile:%s/n",host_file); printf("portnumber:%d/n",portnumber); if((host=gethostbyname(host_addr))==NULL){ fprintf(stderr,"Gethostname error,%s/n",strerror(errno)); exit(1); } if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ fprintf(stderr,"SOcket Error:%s/a/n",strerror(errno)); exit(1);} bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; server_addr.sin_port=htons(portnumber); server_addr.sin_addr=*((struct in_addr *)host->h_addr); if(connect(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1) { fprintf(stderr,"Connect Error:%s/a/n",strerror(errno)); exit(1); } sprintf(request,"GET /%s HTTP/1.1/r/nAccept:*/*/r/nAccept-language:zh-cn/r/n User-Agent:Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)/r/n Host:%s:%d/r/nConnection:Close/r/n/r/n",host_file,host_addr,portnumber); if(host_file && *host_file)pt = Rstrchr(host_file,'/'); else pt=0; memset(local_file,0,sizeof(local_file)); if(pt && *pt){ if((pt+1)&&*(pt+1))strcpy(local_file,pt+1); else memcpy(local_file,host_file,strlen(host_file)-1); } else if(host_file && *host_file)strcpy(local_file,host_file); else strcpy(local_file,"index.html"); printf("local filename to write:%s/n/n",local_file); send=0; totalsend=0; nbytes=strlen(request); while(totalsend<nbytes){ send=write(sockfd,request+totalsend,nbytes-totalsend); if(send==-1){ printf("send error!%s/n",strerror(errno)); exit(0); } totalsend+=send; printf("%d bytes send OK!/n",totalsend); } fp=fopen(local_file,"a"); if(!fp){ printf("create file error!%s/n",strerror(errno)); return 0; } printf("/nThe following is the response header:/n"); i=0; while((nbytes=read(sockfd,buffer,1))==1) if(i<4){ if(buffer[0]=='/r'||buffer[0]=='/n')i++; else i=0; printf("%c",buffer[0]); } else { fwrite(buffer,1,1,fp); i++; if(i%1024==0)fflush(fp); } fclose(fp); close(sockfd); exit(0);}
开发者ID:Furau,项目名称:Practice,代码行数:90,
示例4: mainint main(int argc, char *argv[]) { pid_t sid; char upgfile[512]; int tPid; struct stat stat_buf; int use_storage_firmware = 0; if(argc < 2) { print_usage_exit(1); } /* FIX ME !!! * If we need further parameters for this procedure, then we should use * opt parser and formal parameters. * */ if(argv[1][0] == '-') { switch(argv[1][1]) { case 'b': strcpy(upgfile, "/tmp/mnt/USB/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no /"firmware.bin/" in USB or USB is not inserted/n"); print_usage_exit(1); } else { use_storage_firmware = 1; printf("Using /"firmware.bin/" in USB to upgrade./n"); } strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/USB/firmware.bin"); break; case 's': strcpy(upgfile, "/tmp/mnt/SD/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no /"firmware.bin/" in SD card or SD card is inserted/n"); print_usage_exit(1); } else { use_storage_firmware = 2; printf("Using /"firmware.bin/" in SD card to upgrade./n"); } strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/SD/firmware.bin"); break; case 'a': strcpy(upgfile, "/tmp/mnt/SD/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no /"firmware.bin/" in SD card or SD card is inserted/n"); strcpy(upgfile, "/tmp/mnt/USB/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no /"firmware.bin/" in USB or USB is not inserted/n"); print_usage_exit(1); } else { use_storage_firmware = 1; printf("Using /"firmware.bin/" in USB to upgrade./n"); strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/USB/firmware.bin"); } } else { use_storage_firmware = 2; printf("Using /"firmware.bin/" in SD card to upgrade./n"); strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/SD/firmware.bin"); } break; case 'u': if(argc == 3) { snprintf(upgfile, sizeof(upgfile), "wget %s -O /tmp/firmware 2>&1 | cat > /tmp/fw_log.txt", argv[2]); system(upgfile); if(!check_wget_ok("/tmp/fw_log.txt")) { printf("Unable to get URL %s/n", argv[2]); print_usage_exit(1); } snprintf(upgfile, sizeof(upgfile), "/usr/sbin/ezpup /tmp/firmware"); printf("Get firmware from %s successfully, using /tmp/firmware to upgrade./n", argv[2]); } else { print_usage_exit(1); } break; } } else { snprintf(upgfile, sizeof(upgfile), "/usr/sbin/ezpup %s", argv[1]); } tPid = fork(); if(tPid < 0) { reboot(RB_AUTOBOOT); exit(1); // Error on fork } else if(tPid > 0) { exit(0); } else { FILE *fp; sid = setsid(); if (sid < 0) exit(EXIT_FAILURE);#if defined(PLATFORM_AXA) system("/usr/sbin/ezp-i2c gauge host booting");#endif system("/sbin/stop_services.sh"); system("/sbin/reserve_link.sh");//.........这里部分代码省略.........
开发者ID:choushane,项目名称:Xa-a1a0a8aN,代码行数:101,
示例5: i_parseSequenceinti_parseSequence(DCM_OBJECT ** object){ DCM_ELEMENT e; LST_HEAD *l; CONDITION cond; int index; SQ_TYPE type; SQ_REFRESULTSSOPINSTANCEUID *results; SQ_REQINTERPRETATIONAPPROVER *approver; SQ_REQPROCEDURECODE *diagnosis; void *pointer; static DCM_MAP_SQ sequences[] = { {DCM_IDREFERENCEDRESULTSSEQ, SQ_K_REFRESULTSSOPINSTANCEUID, HIS_K_INTRRSEQUENCE}, {DCM_RESINTERPAPPROVERSEQUENCE, SQ_K_REQINTERPRETATIONAPPROVER, HIS_K_INTIAPPSEQUENCE}, {DCM_RESDIAGNOSISCODESEQ, SQ_K_REQDIAGNOSISCODE, HIS_K_INTIDCSEQUENCE}, }; for (index = 0; index < (int) DIM_OF(sequences); index++) { e.tag = sequences[index].tag; cond = DCM_GetSequenceList(object, e.tag, &e.d.sq); if (cond != DCM_NORMAL) { if (cond != DCM_ELEMENTNOTFOUND) return -1; } else { cond = SQ_ParseSequence(&e, &type, &l); if (cond != SQ_NORMAL || type != sequences[index].type) return -2; p.Update_Flag |= sequences[index].his_field; pointer = LST_Head(&l); if (pointer != NULL) LST_Position(&l, pointer); while (pointer != NULL) { switch (sequences[index].tag) { case DCM_IDREFERENCEDRESULTSSEQ: strcpy(p.RRSequence[p.RRSequenceCount], ((SQ_REFRESULTSSOPINSTANCEUID *) pointer)->referencedSOPInstanceUID); p.RRSequenceCount++; break; case DCM_RESINTERPAPPROVERSEQUENCE: strcpy(p.IApprover[p.IApprovalSequenceCount], ((SQ_REQINTERPRETATIONAPPROVER *) pointer)->physiciansApproving); strcpy(p.IADates[p.IApprovalSequenceCount], ((SQ_REQINTERPRETATIONAPPROVER *) pointer)->approvalDates); strcpy(p.IATimes[p.IApprovalSequenceCount], ((SQ_REQINTERPRETATIONAPPROVER *) pointer)->approvalTimes); p.IApprovalSequenceCount++; break; case DCM_RESDIAGNOSISCODESEQ: strcpy(p.IDCSequence[p.IDCSequenceCount]. CodeValue, ((SQ_REQPROCEDURECODE *) pointer)->codeValue); strcpy(p.IDCSequence[p.IDCSequenceCount]. CodingSchemeDesignator, ((SQ_REQPROCEDURECODE *) pointer)->codingSchemeDesignator); strcpy(p.IDCSequence[p.IDCSequenceCount]. CodeMeaning, ((SQ_REQPROCEDURECODE *) pointer)->codeMeaning); p.IDCSequenceCount++; break; } pointer = LST_Next(&l); } } } return 0;/* e.tag = DCM_IDREFERENCEDRESULTSSEQ; cond = DCM_GetSequenceList(object, e.tag, &e.d.sq); if (cond == DCM_ELEMENTNOTFOUND) return 0; else if (cond != DCM_NORMAL) return -1; cond = SQ_ParseSequence(&e, &type, &l); if (cond != SQ_NORMAL) return -2; if (type == SQ_K_REFRESULTSSOPINSTANCEUID) { p.Update_Flag |= HIS_K_INTRRSEQUENCE; results = LST_Head(&l); if (results != NULL) LST_Position(&l, results); while (results != NULL) { strcpy(p.RRSequence[p.RRSequenceCount], results->referencedSOPInstanceUID); ++p.RRSequenceCount; results = LST_Next(&l); } }*///.........这里部分代码省略.........
开发者ID:nagyistge,项目名称:ctn,代码行数:101,
示例6: funny_namreplyvoid funny_namreply(char *from, char **Args){char *type, *channel;static char format[40];static int last_width = -1;register char *ptr;register char *line;int user_count = 0; PasteArgs(Args, 2); type = Args[0]; channel = Args[1]; line = Args[2]; /* protocol violation by server */ if (!channel || !line) return; ptr = line; while (*ptr) { while (*ptr && (*ptr != ' ')) ptr++; user_count++; while (*ptr && (*ptr == ' ')) ptr++; } if (in_join_list(channel, from_server)) { set_display_target(channel, LOG_CRAP); if (do_hook(current_numeric, "%s %s %s %s", from, type, channel,line) && do_hook(NAMES_LIST, "%s %s", channel, line) && get_int_var(SHOW_CHANNEL_NAMES_VAR)) { put_it("%s", convert_output_format(fget_string_var(FORMAT_NAMES_FSET), "%s %s %d",update_clock(GET_TIME), channel, user_count)); print_funny_names(line); } if ((user_count == 1) && (*line == '@')) { ChannelList *chan; if ((chan = lookup_channel(channel, from_server, CHAN_NOUNLINK))) if ((ptr = get_cset_str_var(chan->csets, CHANMODE_CSET))) my_send_to_server(from_server, "MODE %s %s", channel, ptr); } got_info(channel, from_server, GOTNAMES); reset_display_target(); return; } if (last_width != get_int_var(CHANNEL_NAME_WIDTH_VAR)) { if ((last_width = get_int_var(CHANNEL_NAME_WIDTH_VAR)) != 0) sprintf(format, "%%s: %%-%u.%us %%s", (unsigned char) last_width, (unsigned char) last_width); else strcpy(format, "%s: %s/t%s"); } if (funny_min && (user_count < funny_min)) return; else if (funny_max && (user_count > funny_max)) return; if ((funny_flags & FUNNY_PRIVATE) && (*type == '=')) return; if ((funny_flags & FUNNY_PUBLIC) && ((*type == '*') || (*type == '@'))) return; if (type && channel) { if (match_str) { if (wild_match(match_str, channel) == 0) return; } if (do_hook(current_numeric, "%s %s %s %s", from, type, channel, line) && do_hook(NAMES_LIST, "%s %s", channel, line)) { set_display_target(channel, LOG_CRAP); if (fget_string_var(FORMAT_NAMES_FSET)) { put_it("%s", convert_output_format(fget_string_var(FORMAT_NAMES_FSET), "%s %s %d", update_clock(GET_TIME), channel, user_count)); print_funny_names(line); } else { switch (*type) { case '=': if (last_width &&(strlen(channel) > last_width)) { channel[last_width-1] = '>'; channel[last_width] = (char) 0; } put_it(format, "Pub", channel, line); break; case '*': put_it(format, "Prv", channel, line); break; case '@': put_it(format, "Sec", channel, line); break;//.........这里部分代码省略.........
开发者ID:BitchX,项目名称:BitchX1.1,代码行数:101,
示例7: mainint main(int ac, char **av){ int exp_eno; int lc; char *msg; char osname[OSNAMESZ]; int osnamelth, status; int name[] = { CTL_KERN, KERN_OSTYPE }; pid_t pid; struct passwd *ltpuser; if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); } setup(); if ((tst_kvercmp(2, 6, 32)) <= 0) { exp_eno = EPERM; } else { /* ^^ Look above this warning. ^^ */ tst_resm(TWARN, "this test's results are based on potentially undocumented behavior in the kernel. read the NOTE in the source file for more details"); exp_eno = EACCES; exp_enos[0] = EACCES; } TEST_EXP_ENOS(exp_enos); for (lc = 0; TEST_LOOPING(lc); lc++) { /* reset Tst_count in case we are looping */ Tst_count = 0; strcpy(osname, "Linux"); osnamelth = SIZE(osname); TEST(sysctl(name, SIZE(name), 0, 0, osname, osnamelth)); if (TEST_RETURN != -1) { tst_resm(TFAIL, "sysctl(2) succeeded unexpectedly"); } else { TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == exp_eno) { tst_resm(TPASS | TTERRNO, "Got expected error"); } else if (errno == ENOSYS) { tst_resm(TCONF, "You may need to make CONFIG_SYSCTL_SYSCALL=y" " to your kernel config."); } else { tst_resm(TFAIL | TTERRNO, "Got unexpected error"); } } osnamelth = SIZE(osname); if ((ltpuser = getpwnam("nobody")) == NULL) { tst_brkm(TBROK, cleanup, "getpwnam() failed"); } /* set process ID to "ltpuser1" */ if (seteuid(ltpuser->pw_uid) == -1) { tst_brkm(TBROK, cleanup, "seteuid() failed, errno %d", errno); } if ((pid = FORK_OR_VFORK()) == -1) { tst_brkm(TBROK, cleanup, "fork() failed"); } if (pid == 0) { TEST(sysctl(name, SIZE(name), 0, 0, osname, osnamelth)); if (TEST_RETURN != -1) { tst_resm(TFAIL, "call succeeded unexpectedly"); } else { TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == exp_eno) { tst_resm(TPASS | TTERRNO, "Got expected error"); } else if (TEST_ERRNO == ENOSYS) { tst_resm(TCONF, "You may need to make CONFIG_SYSCTL_SYSCALL=y" " to your kernel config."); } else { tst_resm(TFAIL | TTERRNO, "Got unexpected error"); } } cleanup(); } else { /* wait for the child to finish */ wait(&status); }//.........这里部分代码省略.........
开发者ID:Nan619,项目名称:ltp-ddt,代码行数:101,
示例8: rgzmat//.........这里部分代码省略......... if (index0 != -1) { if (overflow_flag == 0) { sscanf(line, "%s%d%s%d%s%d%s", atom[numatom].name, &atom[numatom].bondatom, bondstr[numatom].name, &atom[numatom].angleatom, anglestr[numatom].name, &atom[numatom].twistatom, twiststr[numatom].name); if(atom[numatom].bondatom > numatom) { printf("/nError: bond atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } if(atom[numatom].angleatom > numatom) { printf("/nError: angle atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } if(atom[numatom].twistatom > numatom) { printf("/nError: torsional atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } } numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("/nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index0 == -1) { if (strchr(line, '=') == NULL) continue; coordinate_flag = 1; for(i=0;i<strlen(line);i++) if(line[i] == '=') line[i] = ' '; sscanf(line, "%s %s", tmpchar1, tmpchar2); for (i = 1; i < numatom; i++) { findindex = 1; for (j = 0; j < strlen(bondstr[i].name); j++) if (bondstr[i].name[j] != tmpchar1[j]) { findindex = 0; break; } if (findindex == 1) { strcpy(bondstr[i].name, tmpchar2); break; } } for (i = 2; i < numatom; i++) { findindex = 1; for (j = 0; j < strlen(anglestr[i].name); j++) if (anglestr[i].name[j] != tmpchar1[j]) { findindex = 0; break; } if (findindex == 1) { strcpy(anglestr[i].name, tmpchar2); break; } } for (i = 3; i < numatom; i++) { findindex = 1; for (j = 0; j < strlen(twiststr[i].name); j++) if (twiststr[i].name[j] != tmpchar1[j]) { findindex = 0; break; } if (findindex == 1) { strcpy(twiststr[i].name, tmpchar2); break; } } } } atom[1].bondatom--; atom[2].bondatom--; atom[2].angleatom--; for (i = 3; i < numatom; i++) { atom[i].bondatom--; atom[i].angleatom--; atom[i].twistatom--; } for (i = 1; i < numatom; i++) atom[i].bond = atof(bondstr[i].name); for (i = 2; i < numatom; i++) atom[i].angle = atof(anglestr[i].name); for (i = 3; i < numatom; i++) atom[i].twist = atof(twiststr[i].name); *atomnum = numatom;/* printf("/n atom number is %5d", *atomnum); */ fclose(fpin); free(bondstr); free(anglestr); free(twiststr); return overflow_flag;}
开发者ID:tianhe2,项目名称:mAMBER,代码行数:101,
示例9: wgzmatvoid wgzmat(char *filename, int atomnum, ATOM atom[], MOLINFO minfo){ FILE *fpin; FILE *fpout; char *amberhome; char espparm_file[MAXCHAR]; char line[MAXCHAR]; char akeyword[MAXCHAR]=""; char ckeyword[MAXCHAR]; char tmpchar0[MAXCHAR]; char tmpchar1[MAXCHAR]; char tmpchar2[MAXCHAR]; char tmpchar3[MAXCHAR]; int i,j; int iradius_flag; int ibs= 0; int esp_flag; int nespparm = 0; int nbasisset = 0; double default_radius = 1.7; ESPPARM espparm[120]; BASISSET basisset[100]; if ((fpout = fopen(filename, "w")) == NULL) { fprintf(stdout, "Cannot open a file %s to write in wgzmat(), exit/n", filename); exit(1); } intercoord(atomnum, atom); fprintf(fpout, "%s/n", "--Link1--"); if(strlen(minfo.gn) >= 5) fprintf(fpout, "%s/n", minfo.gn); fprintf(fpout, "%s%s/n", "%chk=", minfo.chkfile); if(strlen(minfo.gm) >= 4) fprintf(fpout, "%s/n", minfo.gm);// check ESP-related keyword esp_flag = 0; for(i=0;i<strlen(minfo.gkeyword);i++) ckeyword[i] = toupper(minfo.gkeyword[i]); if((strstr(ckeyword, "POP=") != 0 || strstr(ckeyword, "POP(") != 0) && (strstr(ckeyword, "MK") != 0 || strstr(ckeyword, "CHELP") != 0)) esp_flag = 1;// when the default gaussian keyword is used, or esp_flag ==1, read ESP.PARM if(minfo.igkeyword == 0 || esp_flag == 1) { amberhome = (char *) getenv("AMBERHOME"); if( amberhome == NULL ){ fprintf( stdout, "AMBERHOME is not set!/n" ); exit(1); } strcpy(espparm_file, amberhome); strcat(espparm_file, "/dat/antechamber/ESPPARM.DAT"); if ((fpin = fopen(espparm_file, "r")) == NULL) { fprintf(stdout, "Cannot open espparm_file %s in read_espparm(), exit/n", espparm_file); exit(1); } for (;;) { if (fgets(line, MAXCHAR, fpin) == NULL) break; if(strncmp(line, "DEFAULT RADIUS", 14) == 0) sscanf(&line[14], "%lf", &default_radius); if(strncmp(line, "BASIS SET", 9) == 0) { sscanf(&line[9], "%d%s", &basisset[nbasisset].id, basisset[nbasisset].bs); nbasisset++; } if(strncmp(line, "PARM", 4) == 0) { sscanf(&line[4], "%ld%s%lf%lf%d%d", &espparm[nespparm].atomicnum, espparm[nespparm].elem, &espparm[nespparm].vdw, &espparm[nespparm].mk, &espparm[nespparm].flag, &espparm[nespparm].bs); nespparm++; } } fclose(fpin); iradius_flag = 0; ibs = 0; for(i=0;i<atomnum;i++) { for(j=0;j<nespparm;j++) if(atom[i].atomicnum == espparm[j].atomicnum || strcmp(atom[i].element, espparm[j].elem) == 0) { if(ibs < espparm[j].bs) ibs=espparm[j].bs; if(espparm[j].flag != 0) { iradius_flag = 1; espparm[j].flag = 2; } break; } } if(minfo.igkeyword == 0) { strcpy(minfo.gkeyword, "#HF/"); strcat(minfo.gkeyword, basisset[ibs-1].bs); strcat(minfo.gkeyword, " SCF=tight Test Pop=MK iop(6/33=2) iop(6/42=6) opt"); } }// additional keywords if(esp_flag == 1) { if(iradius_flag == 1) { if(strstr(minfo.gkeyword, "ReadRadii") == 0 && strstr(minfo.gkeyword, "READRADII") == 0 && strstr(minfo.gkeyword, "readradii") == 0) {//.........这里部分代码省略.........
开发者ID:tianhe2,项目名称:mAMBER,代码行数:101,
示例10: IoCtlMyDriver//===============================================================================================//===== Функция IO Control//===============================================================================================NTSTATUS IoCtlMyDriver(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp){ MegaDriverData *pdata; NTSTATUS status = STATUS_SUCCESS; ULONG BytesCount =0; // Число переданных/полученных байт (пока 0) PIO_STACK_LOCATION IrpStack=IoGetCurrentIrpStackLocation(Irp); UCHAR *buff;//for byte // Получаем указатель на расширение устройства PEXAMPLE_DEVICE_EXTENSION dx = (PEXAMPLE_DEVICE_EXTENSION)DeviceObject->DeviceExtension; // Выделяем из IRP значение IOCTL кода (причина вызова) ULONG ControlCode = IrpStack->Parameters.DeviceIoControl.IoControlCode; //лог DbgPrint(" >MegaDriver: IoCtlDriver - we are in"); //-------------------------------------------------------------------------------------------------------------- switch(ControlCode) { //тут нам прислали структурку с двумя строкаме case IOCTL_SEND_DATA_STRUCT: BytesCount = IrpStack->Parameters.DeviceIoControl.InputBufferLength; if(DataSize == BytesCount) { //=================================================================================================== //===== Получаем параметры //=================================================================================================== DbgPrint(" >MegaDriver: IoCtlDriver -> Check BufferIn Size - [ok]"); //проверяем параметр if(((MegaDriverData*)Irp->AssociatedIrp.SystemBuffer)->procToFind == NULL) { DbgPrint(" >MegaDriver: IoCtlDriver -> Input Params == NULL"); break;//сваливаем нахер, ибо иначе может быть бсод... } //copy data strcpy(gData.procToFind, ((MegaDriverData*)Irp->AssociatedIrp.SystemBuffer)->procToFind); strcpy(gData.procToOpen, ((MegaDriverData*)Irp->AssociatedIrp.SystemBuffer)->procToOpen); //show what we have DbgPrint(" >MegaDriver: IoCtlDriver -> Input Params:"); DbgPrint(" >MegaDriver: IoCtlDriver -> procToFind %s", gData.procToFind); DbgPrint(" >MegaDriver: IoCtlDriver -> procToOpen %s", gData.procToOpen); //if not BSOD =) gInited = TRUE; //Шикарно... тут мы приняли параметрЫ !!! //создаем нотифаер на создание нового процесса в системе PsSetCreateProcessNotifyRoutine(NotifyRoutine, FALSE); //=================================================================================================== //===== Чонить отсылаем обратно //=================================================================================================== pdata = (MegaDriverData*)Irp->AssociatedIrp.SystemBuffer; strcpy(gData.status, "all data accepted");//нипашет пока strcpy(pdata->procToFind, "11111111111"); strcpy(pdata->procToOpen, "22222222222"); if(FindProcess(FindBuffer)) { DbgPrint(" >MegaDriver: +++ PROCESS FOUND +++"); strcpy(pdata->status, "found"); } else { strcpy(pdata->status, "not found"); } Irp->IoStatus.Information = sizeof(gData); DbgPrint(" >MegaDriver: IoCtlDriver -> Status: %s", pdata->status); //осталось всеголишь найти нужный процесс))) //IoRequestDpc( //create DPC //IoInitializeDpcRequest //KeInsertQueueDpc //PsCreateSystemThread//IRQL_PASSIVE_LEVEL //WriteToFile("First test string from IoCtl /r/n"); //--------- } else DbgPrint(" >MegaDriver: IoCtlDriver -> Check BufferIn Size - [failed]"); break; case IOCTL_JUST_CHECK_STATUS: pdata = (MegaDriverData*)Irp->AssociatedIrp.SystemBuffer; strcpy(gData.status, "all data accepted");//нипашет пока strcpy(pdata->procToFind, "11111111111"); strcpy(pdata->procToOpen, "22222222222"); if(FindProcess(FindBuffer)) { DbgPrint(" >MegaDriver: +++ PROCESS FOUND +++"); strcpy(pdata->status, "found"); } else {//.........这里部分代码省略.........
开发者ID:340211173,项目名称:Driver,代码行数:101,
示例11: main//.........这里部分代码省略......... SNOWTABLE *SnowAlbedo = NULL; SOILPIX **SoilMap = NULL; SEDPIX **SedMap = NULL; SOILTABLE *SType = NULL; SEDTABLE *SedType = NULL; SOLARGEOMETRY SolarGeo; /* Geometry of Sun-Earth system (needed for INLINE radiation calculations */ TIMESTRUCT Time; TOPOPIX **TopoMap = NULL; UNITHYDR **UnitHydrograph = NULL; UNITHYDRINFO HydrographInfo; /* Information about unit hydrograph */ VEGPIX **VegMap = NULL; VEGTABLE *VType = NULL; WATERBALANCE Mass = /* parameter for mass balance calculations */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };/***************************************************************************** Initialization Procedures *****************************************************************************/ if (argc != 2) { fprintf(stderr, "/nUsage: %s inputfile/n/n", argv[0]); fprintf(stderr, "DHSVM uses two output streams: /n"); fprintf(stderr, "Standard Out, for the majority of output /n"); fprintf(stderr, "Standard Error, for the final mass balance /n"); fprintf(stderr, "/nTo pipe output correctly to files: /n"); fprintf(stderr, "(cmd > f1) >& f2 /n"); fprintf(stderr, "where f1 is stdout_file and f2 is stderror_file/n"); exit(EXIT_FAILURE); } sprintf(commandline, "%s %s", argv[0], argv[1]); printf("%s /n", commandline); fprintf(stderr, "%s /n", commandline); strcpy(InFiles.Const, argv[1]); printf("/nRunning DHSVM %s/n", version); printf("/nSTARTING INITIALIZATION PROCEDURES/n/n"); /* Start recording time */ start = clock(); ReadInitFile(InFiles.Const, &Input); InitConstants(Input, &Options, &Map, &SolarGeo, &Time); InitFileIO(Options.FileFormat); InitTables(Time.NDaySteps, Input, &Options, &SType, &Soil, &VType, &Veg, &SnowAlbedo); InitTerrainMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &VegMap); CheckOut(Options.CanopyRadAtt, Veg, Soil, VType, SType, &Map, TopoMap, VegMap, SoilMap); if (Options.HasNetwork) InitChannel(Input, &Map, Time.Dt, &ChannelData, SoilMap, &MaxStreamID, &MaxRoadID, &Options); else if (Options.Extent != POINT) InitUnitHydrograph(Input, &Map, TopoMap, &UnitHydrograph, &Hydrograph, &HydrographInfo); InitNetwork(Map.NY, Map.NX, Map.DX, Map.DY, TopoMap, SoilMap, VegMap, VType, &Network, &ChannelData, Veg, &Options); InitMetSources(Input, &Options, &Map, Soil.MaxLayers, &Time, &InFiles, &NStats, &Stat, &Radar, &MM5Map); /* the following piece of code is for the UW PRISM project */
开发者ID:Lizzy0Sun,项目名称:DHSVM_RBM,代码行数:67,
示例12: mainint main(int argc, char **argv){ options_t options; int doversion = 0; int dohelp = 0; int userclasses = 0; int ch; int option_index = 0; char prefix[IF_NAMESIZE + 3]; pid_t pid; const struct option longopts[] = { {"arp", no_argument, NULL, 'a'}, {"script",required_argument, NULL, 'c'}, {"debug", no_argument, NULL, 'd'}, {"hostname", required_argument, NULL, 'h'}, {"classid", required_argument, NULL, 'i'}, {"release", no_argument, NULL, 'k'}, {"leasetime", required_argument, NULL, 'l'}, {"metric", required_argument, NULL, 'm'}, {"renew", no_argument, NULL, 'n'}, {"persistent", no_argument, NULL, 'p'}, {"request", required_argument, NULL, 's'}, {"timeout", required_argument, NULL, 't'}, {"userclass", required_argument, NULL, 'u'}, {"fqdn", optional_argument, NULL, 'F'}, {"nogateway", no_argument, NULL, 'G'}, {"sethostname", no_argument, NULL, 'H'}, {"clientid", required_argument, NULL, 'I'}, {"nontp", no_argument, NULL, 'N'}, {"nodns", no_argument, NULL, 'R'}, {"nonis", no_argument, NULL, 'Y'}, {"help", no_argument, &dohelp, 1}, {"version", no_argument, &doversion, 1}, {NULL, 0, NULL, 0} }; /* Sanitize our fd's */ int zero; if ((zero = open (_PATH_DEVNULL, O_RDWR, 0)) >= 0) { while (zero < 3) zero = dup (zero); close(zero); } openlog (PACKAGE, LOG_PID, LOG_LOCAL0); memset (&options, 0, sizeof (options_t)); options.script = (char *) DEFAULT_SCRIPT; snprintf (options.classid, CLASS_ID_MAX_LEN, "%s %s", PACKAGE, VERSION); options.doarp = false; options.dodns = true; options.donis = true; options.dontp = true; options.dogateway = true; gethostname (options.hostname, sizeof (options.hostname)); if (strcmp (options.hostname, "(none)") == 0 || strcmp (options.hostname, "localhost") == 0) memset (options.hostname, 0, sizeof (options.hostname)); options.timeout = DEFAULT_TIMEOUT; while ((ch = getopt_long(argc, argv, "ac:dh:i:kl:m:nps:t:u:F:GHI:NRY", longopts, &option_index)) != -1) switch (ch) { case 0: if (longopts[option_index].flag) break; logger (LOG_ERR, "option `%s' should set a flag", longopts[option_index].name); exit (EXIT_FAILURE); break; case 'a': options.doarp = true; break; case 'c': options.script = optarg; break; case 'd': setloglevel(LOG_DEBUG); break; case 'h': if (strlen (optarg) > HOSTNAME_MAX_LEN) { logger(LOG_ERR, "`%s' too long for HostName string, max is %d", optarg, HOSTNAME_MAX_LEN); exit (EXIT_FAILURE); } else strcpy (options.hostname, optarg); break; case 'i': if (strlen(optarg) > CLASS_ID_MAX_LEN) { logger (LOG_ERR, "`%s' too long for ClassID string, max is %d", optarg, CLASS_ID_MAX_LEN);//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:dhcpcd-svn,代码行数:101,
示例13: dsetRead_devAiAsyncSerial/*----------------------------------------------------------------------*/static long dsetRead_devAiAsyncSerial(aiRecord *pai) { CONTEXT *p_myContext; char p_writeBuffer[BUFLEN]; char p_readBuffer[BUFLEN]; int myPortNumber; char p_myCommand[BUFLEN]; #ifdef DEBUG1 printf( __FILE__ "[%d] -> %s/n", __LINE__, __func__); #endif p_myContext = (CONTEXT *)pai->dpvt; myPortNumber=p_myContext->portNumber; strcpy(p_myCommand,p_myContext->p_command); /* Get the lock or callback */ if (lockSerialPort2(myPortNumber,LOCK, pai->name)<=ERROR) { #ifdef DEBUG2 printf( __FILE__ "[%d] Error: Couldn't lock %s/n", __LINE__, getSerialPortName2(myPortNumber)); printf( __FILE__ "[%d] lockOwner is %s/n", __LINE__, getSerialPortLockOwner2(myPortNumber)); #endif pai->pact=TRUE; callbackRequestDelayed(p_myContext->p_callback,SLEEPTIME_CALLBACK); return(NO_CONVERSION); } /* end_of_if */ /* construct request for the pressure */ /* strcat(p_writeBuffer,"P"); sprintf(str,"%d",p_myContext->secondaryAddress); */ strcpy(p_writeBuffer,p_myCommand); strcat(p_writeBuffer,TERMINATOR); #ifdef DEBUG2 printf( __FILE__ "[%d] Writing >%s< for %s on %s/n", __LINE__, p_writeBuffer, pai->name, getSerialPortName2(myPortNumber)); #endif if (writeSerialPort2(myPortNumber, p_writeBuffer)<= ERROR) { printf( __FILE__ "[%d] Error: Couldn't write >%s< to %s/n", __LINE__, p_writeBuffer, pai->name); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_WRITE); if (readSerialPort2(myPortNumber, p_readBuffer,BUFLEN)<=ERROR) { printf( __FILE__ "[%d] Error: Couldn't Read %s/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } #ifdef DEBUG2 printf( __FILE__ "[%d] %s read >%s</n", __LINE__, pai->name, p_readBuffer); #endif usleep(USLEEPTIME_READ); if (lockSerialPort2(myPortNumber, UNLOCK, pai->name) <=ERROR) { printf( __FILE__ "[%d] Error: Couldn't unlock %s/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } if ( (strncmp(p_readBuffer,"HV_OFF!",7)==0) || (strncmp(p_readBuffer,"WAIT",4)==0) || (strncmp(p_readBuffer,"CONTROL!",8)==0) || (strncmp(p_readBuffer,"PROTECT!",8)==0) || (strncmp(p_readBuffer,"NOGAUGE!",8)==0)) { printf( __FILE__ "[%d] Error: Check the probe/n", __LINE__); printf( __FILE__ "[%d] Error: Check the hardware/n", __LINE__); pai->udf = TRUE; } else { pai->val = atof(p_readBuffer); pai->udf = FALSE; } pai->pact = FALSE; #ifdef DEBUG2 printf( __FILE__ "[%d] <- %s/n", __LINE__, __func__); #endif return(NO_CONVERSION); }
开发者ID:emayssat,项目名称:epics-iocs,代码行数:92,
示例14: dsetInit_devAiAsyncSerial/* initialize the epics record and the hardware */static long dsetInit_devAiAsyncSerial(aiRecord *pai){ CONTEXT *p_myContext; CALLBACK *p_myCallback; char p_writeBuffer[BUFLEN]; char p_readBuffer[BUFLEN]; int myPrimaryAddress; int myPortNumber; int myParity; int myNumberOfDataBits; int myNumberOfStopBits; int myBaudRate; char p_myCommand[BUFLEN]; #ifdef DEBUG1 packageInfo(); printf(__FILE__ "[%d] -> %s (%s)/n", __LINE__, __func__, pai->name); #endif /* Parse the db file paramters */ /* and set the value of key variables */ if(sscanf(pai->inp.value.instio.string, "spn=%d pad=%d br=%d nodb=%d p=%d nosb=%d c=%[^/n]", &myPortNumber, &myPrimaryAddress, &myBaudRate, &myNumberOfDataBits, &myParity, &myNumberOfStopBits, p_myCommand)!=7) { printf( __FILE__ "[%d] Error: Couldn't parse the parameters correctly!", __LINE__ ); printf( __FILE__ "[%d] >%s<!", __LINE__, pai->inp.value.instio.string ); sleep(SLEEPTIME_ERROR); return(ERROR); } /* end_of_if */ initSerialPort2(myPortNumber); setBaudRate2(myPortNumber,myBaudRate); setNumberOfDataBits2(myPortNumber,myNumberOfDataBits); setParity2(myPortNumber,myParity); setFlowControl2(myPortNumber,NO_FLOW_CONTROL); /* Required for this dev */ setNumberOfStopBits2(myPortNumber,myNumberOfStopBits); #ifdef DEBUG2 printf(__FILE__ "[%d] portNumber = %d/n", __LINE__, myPortNumber); printf(__FILE__ "[%d] primaryAddress = %d/n", __LINE__, myPrimaryAddress); printf(__FILE__ "[%d] baudRate = %d/n", __LINE__, getBaudRate2(myPortNumber)); printf(__FILE__ "[%d] numberOfDataBits = %d/n", __LINE__, getNumberOfDataBits2(myPortNumber)); printf(__FILE__ "[%d] parity = %d/n", __LINE__, getParity2(myPortNumber)); printf(__FILE__ "[%d] numberOfStopBits = %d/n", __LINE__, getNumberOfStopBits2(myPortNumber)); printf(__FILE__ "[%d] p_myCommand = >%s</n", __LINE__, p_myCommand); #endif if (lockSerialPort2(myPortNumber,LOCK, pai->name)<=ERROR) { printf( __FILE__ "[%d] Error: Couldn't lock serial port (%s)/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } /* Disable front panel */ /* This operation should work if */ /* communication parameters are ok */ strcpy(p_writeBuffer,"XFRONT"); strcat(p_writeBuffer,TERMINATOR); openSerialPort2(myPortNumber); if (writeSerialPort2(myPortNumber, p_writeBuffer ) <= ERROR) { printf( __FILE__ "[%d] Error: Couldn't write on %s/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_WRITE); memset(p_readBuffer,0,BUFLEN); if (readSerialPort2(myPortNumber, p_readBuffer, BUFLEN) <= ERROR) { printf( __FILE__ "[%d] Error: Couldn't read on %s/n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_READ); if (lockSerialPort2(myPortNumber,UNLOCK, pai->name)<=ERROR) { printf ( __FILE__ "Error"); sleep(SLEEPTIME_ERROR); return(ERROR); } p_myCallback=(CALLBACK *)calloc(1,sizeof(CALLBACK)); callbackSetCallback(myCallback_devAiAsyncSerial,p_myCallback); callbackSetUser(pai,p_myCallback); p_myContext=(CONTEXT *)calloc(1,sizeof(CONTEXT)); p_myContext->portNumber=myPortNumber;//.........这里部分代码省略.........
开发者ID:emayssat,项目名称:epics-iocs,代码行数:101,
示例15: find_wireless_nicvoid find_wireless_nic(void){ static int found = 0; FILE *file; int sock; struct ifreq ifr; struct ethtool_value ethtool; struct ethtool_drvinfo driver; int ret; if (found++) return; wireless_nic[0] = 0; rfkill_path[0] = 0; powersave_path[0] = 0; strcpy(wireless_nic, "wlan0"); file = popen("/sbin/iwpriv -a 2> /dev/null", "r"); if (!file) return; while (!feof(file)) { char line[1024]; memset(line, 0, 1024); if (fgets(line, 1023, file)==NULL) break; if (strstr(line, "get_power:Power save level")) { char *c; c = strchr(line, ' '); if (c) *c = 0; strcpy(wireless_nic, line); } if (strstr(line, "wlan0:")) strcpy(wireless_nic, "wlan0"); } pclose(file); if (strlen(wireless_nic)==0) return; memset(&ifr, 0, sizeof(struct ifreq)); memset(ðtool, 0, sizeof(struct ethtool_value)); sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock<0) return; strcpy(ifr.ifr_name, wireless_nic); /* Check if the interface is up */ ret = ioctl(sock, SIOCGIFFLAGS, &ifr); if (ret<0) { close(sock); return; } memset(&driver, 0, sizeof(driver)); driver.cmd = ETHTOOL_GDRVINFO; ifr.ifr_data = (void*) &driver; ret = ioctl(sock, SIOCETHTOOL, &ifr); sprintf(rfkill_path,"/sys/bus/pci/devices/%s/rfkill/rfkill0/state", driver.bus_info); sprintf(powersave_path,"/sys/bus/pci/devices/%s/power_level", driver.bus_info); close(sock);}
开发者ID:kernelzilla,项目名称:android_external_powertop,代码行数:68,
示例16: mainint main(int argc, char *argv[]){ char inFile[512], *configFile=NULL, type[10]; const int pid = getpid(); extern int logflag, quietflag; int quiet_f; /* log_f is a static global */ int createFlag = FLAG_NOT_SET; // create configuration file flag int configFlag = FLAG_NOT_SET; // use configuration file flag logflag = quietflag = FALSE; log_f = quiet_f = FLAG_NOT_SET; // Begin command line parsing *********************************************** if ( (checkForOption("--help", argc, argv) != FLAG_NOT_SET) || (checkForOption("-h", argc, argv) != FLAG_NOT_SET) || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) { print_help(); } get_asf_share_dir_with_argv0(argv[0]); handle_license_and_version_args(argc, argv, ASF_NAME_STRING); // Check which options were provided log_f = checkForOption("-log", argc, argv); quiet_f = checkForOption("-quiet", argc, argv); createFlag = checkForOption("-create", argc, argv); configFlag = checkForOption("-config", argc, argv); // We need to make sure the user specified the proper number of arguments int needed_args = 1 + REQUIRED_ARGS; // command & REQUIRED_ARGS int num_flags = 0; if (log_f != FLAG_NOT_SET) {needed_args += 2; num_flags++;} // option & param if (quiet_f != FLAG_NOT_SET) {needed_args += 1; num_flags++;} // option if (createFlag != FLAG_NOT_SET) {needed_args += 3; num_flags++;} // option & params if (configFlag != FLAG_NOT_SET) {needed_args += 2; num_flags++;} // option & param // Make sure we have the right number of args if(argc != needed_args) { print_usage(); } // Make sure all options occur before the config file name argument if (num_flags == 1 && (log_f > 1 || quiet_f > 1)) { print_usage(); } else if (num_flags > 1 && (log_f >= argc - REQUIRED_ARGS - 1 || quiet_f >= argc - REQUIRED_ARGS - 1)) { print_usage(); } // Make sure that only one option is used if (createFlag != FLAG_NOT_SET && configFlag != FLAG_NOT_SET) asfPrintError("The tool can either create or use the " "configuration file, not both!/n"); // Do the actual flagging & such for each flag if (createFlag != FLAG_NOT_SET) { sprintf(type, "%s", argv[createFlag+1]); configFile = (char *) MALLOC(sizeof(char)*1024); sprintf(configFile, "%s", argv[createFlag+2]); } if (configFlag != FLAG_NOT_SET) { configFile = (char *) MALLOC(sizeof(char)*1024); sprintf(configFile, "%s", argv[configFlag+1]); } if (log_f != FLAG_NOT_SET) { strcpy(logFile, argv[log_f+1]); } else { // default behavior: log to tmp<pid>.log sprintf(logFile, "tmp%i.log", pid); } logflag = TRUE; fLog = FOPEN(logFile, "a"); // Set old school quiet flag (for use in our libraries) quietflag = quiet_f != FLAG_NOT_SET; // Fetch required arguments strcpy(inFile, argv[argc-1]); // Report the command line asfSplashScreen(argc, argv); // Initialze structure dataset_t *data = (dataset_t *) MALLOC(sizeof(dataset_t)); strcpy(data->dataset_id, MAGIC_UNSET_STRING); strcpy(data->origin, MAGIC_UNSET_STRING); strcpy(data->title, MAGIC_UNSET_STRING); strcpy(data->online_link, MAGIC_UNSET_STRING); data->west_bounding = MAGIC_UNSET_DOUBLE; data->east_bounding = MAGIC_UNSET_DOUBLE; data->north_bounding = MAGIC_UNSET_DOUBLE; data->south_bounding = MAGIC_UNSET_DOUBLE; data->near_start_lat = MAGIC_UNSET_DOUBLE; data->near_start_lon = MAGIC_UNSET_DOUBLE;//.........这里部分代码省略.........
开发者ID:DavinSimmons,项目名称:ASF_MapReady,代码行数:101,
示例17: strcpyvoid UDPServer::send(const std::string &s) { char buf[BUF_SIZE]; strcpy(buf, s.c_str()); socklen_t len = sizeof(_cliaddr); sendto(_sockfd, buf, strlen(buf), 0, (SA *)&_cliaddr, len); }
开发者ID:darthvade,项目名称:PersonalExercise,代码行数:6,
示例18: menu_requestfilechar* menu_requestfile(char* file, char *title, char* path, char *exts){ char *dir; int allocmem = file == NULL; int tmplen = 0; char parent_dir_str[5];#ifdef DINGOO_NATIVE static char dingoo_default_path[]="A://";#endif /* DINGOO_NATIVE */ /* TODO clear all the dyanamic memory allocations in this routine and require caller to pre-allocate */ if (allocmem) file = malloc(PATH_MAX);#ifdef DEBUG_ALWAYS_RETURN_ADJUSTRIS_GB strcpy(file, "adjustris.gb"); return file;#endif /* DEBUG_ALWAYS_RETURN_ADJUSTRIS_GB */ if(path) { strcpy(file, path); tmplen = strlen(file); if (tmplen >=1) { if (file[tmplen-1] != DIRSEP_CHAR) strcat(file, DIRSEP); /* this is very fragile, e.g. what if dir was specified but does not exist */ } } else strcpy(file, ""); snprintf(parent_dir_str, sizeof(parent_dir_str), "..%s", DIRSEP); while(dir = menu_browsedir(file, file+strlen(file),title,exts)){ if (!strcmp(dir, parent_dir_str)) { /* need to go up a directory */ dir--; if (dir > file) { *dir = '/0'; while (dir >= file && *dir != DIRSEP_CHAR) { *dir = '/0'; dir--; } } if (strlen(file) == 0) {#ifdef DINGOO_NATIVE if (dingoo_default_path[0] == 'A') dingoo_default_path[0] = 'B'; else dingoo_default_path[0] = 'A'; sprintf(file, "%s", dingoo_default_path); /* ** If there is no MiniSD card in B: ** then an empty list is displayed ** click the parent directory to ** toggle back to A: */#else sprintf(file, ".%s", DIRSEP);#endif /* DINGOO_NATIVE */ dir = file + strlen(file)+1; *dir = '/0'; } } /* ** Check to see if we have a file name, ** or a new directory name to scan ** Directory name will have trailing path sep character ** FIXME check for "../" and dirname the dir */ tmplen = strlen(dir); if (tmplen >=1) if (dir[tmplen-1] != DIRSEP_CHAR) { if (allocmem) file = realloc(file, strlen(file)+1); break; } } if(!dir) file = NULL; /* FIXME what it file was not null when function was called, what about free'ing this is we allocated it? */ return file;}
开发者ID:ionbladez,项目名称:ohboy-zipit,代码行数:84,
示例19: offb_init_fbstatic void __init offb_init_fb(const char *name, const char *full_name, int width, int height, int depth, int pitch, unsigned long address, int foreign_endian, struct device_node *dp){ unsigned long res_size = pitch * height * (depth + 7) / 8; struct offb_par *par = &default_par; unsigned long res_start = address; struct fb_fix_screeninfo *fix; struct fb_var_screeninfo *var; struct fb_info *info; if (!request_mem_region(res_start, res_size, "offb")) return; printk(KERN_INFO "Using unsupported %dx%d %s at %lx, depth=%d, pitch=%d/n", width, height, name, address, depth, pitch); if (depth != 8 && depth != 15 && depth != 16 && depth != 32) { printk(KERN_ERR "%s: can't use depth = %d/n", full_name, depth); release_mem_region(res_start, res_size); return; } info = framebuffer_alloc(sizeof(u32) * 16, NULL); if (info == 0) { release_mem_region(res_start, res_size); return; } fix = &info->fix; var = &info->var; info->par = par; strcpy(fix->id, "OFfb "); strncat(fix->id, name, sizeof(fix->id) - sizeof("OFfb ")); fix->id[sizeof(fix->id) - 1] = '/0'; var->xres = var->xres_virtual = width; var->yres = var->yres_virtual = height; fix->line_length = pitch; fix->smem_start = address; fix->smem_len = pitch * height; fix->type = FB_TYPE_PACKED_PIXELS; fix->type_aux = 0; par->cmap_type = cmap_unknown; if (depth == 8) offb_init_palette_hacks(info, dp, name, address); else fix->visual = FB_VISUAL_TRUECOLOR; var->xoffset = var->yoffset = 0; switch (depth) { case 8: var->bits_per_pixel = 8; var->red.offset = 0; var->red.length = 8; var->green.offset = 0; var->green.length = 8; var->blue.offset = 0; var->blue.length = 8; var->transp.offset = 0; var->transp.length = 0; break; case 15: /* RGB 555 */ var->bits_per_pixel = 16; var->red.offset = 10; var->red.length = 5; var->green.offset = 5; var->green.length = 5; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; break; case 16: /* RGB 565 */ var->bits_per_pixel = 16; var->red.offset = 11; var->red.length = 5; var->green.offset = 5; var->green.length = 6; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; break; case 32: /* RGB 888 */ var->bits_per_pixel = 32; var->red.offset = 16; var->red.length = 8; var->green.offset = 8; var->green.length = 8; var->blue.offset = 0; var->blue.length = 8; var->transp.offset = 24; var->transp.length = 8;//.........这里部分代码省略.........
开发者ID:CSCLOG,项目名称:beaglebone,代码行数:101,
示例20: mallocchar *menu_requestdir(const char *title, const char *path){ char *dir=NULL, **ldirs; int ldirsz, ldirn=0, ret, l; DIR *cd; struct dirent *d;#ifndef DT_DIR struct stat s;#endif /* DT_DIR */ char *cdpath; //#ifndef DT_DIR char tmpfname[PATH_MAX]; char *tmpfname_end;//#endif /* DT_DIR */ cdpath = malloc(PATH_MAX); strcpy(cdpath, path);//#ifndef DT_DIR strcpy(tmpfname, path); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname);//#endif /* DT_DIR */ while(!dir){ cd = opendir(cdpath); dialog_begin(title, cdpath); dialog_text("[Select This Directory]",NULL,FIELD_SELECTABLE); dialog_text("/.. Parent Directory",NULL,FIELD_SELECTABLE); ldirsz = 16; ldirs = malloc(sizeof(char*)*ldirsz); d = readdir(cd); if(d && !strcmp(d->d_name,".")) d = readdir(cd); if(d && !strcmp(d->d_name,"..")) d = readdir(cd); while(d){ if(ldirn >= ldirsz){ ldirsz += 16; ldirs = realloc(ldirs,ldirsz*sizeof(char*)); }#ifndef DT_DIR /* can not lookup type from search result have to stat filename*/ strcpy(tmpfname_end, d->d_name); stat(tmpfname, &s); if(S_ISDIR (s.st_mode))#else if ((d->d_type & DT_DIR) == DT_DIR)#endif /* DT_DIR */ { l = strlen(d->d_name); ldirs[ldirn] = malloc(l+2); strcpy(ldirs[ldirn], d->d_name); ldirs[ldirn][l] = DIRSEP_CHAR; ldirs[ldirn][l+1] = '/0'; dialog_text(ldirs[ldirn],NULL,FIELD_SELECTABLE); ldirn++; } d = readdir(cd); } closedir(cd); switch(ret=dialog_end()){ case 0: dir = (char*)-1; break; case 1: dir = strdup(cdpath); break; case 2: { /* need to go up a directory */ char *tmp_str=NULL; tmp_str=cdpath; tmp_str+=strlen(tmp_str)-1; tmp_str--; if (tmp_str > cdpath) { *tmp_str = '/0'; while (tmp_str >= cdpath && *tmp_str != DIRSEP_CHAR) { *tmp_str = '/0'; tmp_str--; } } if (strlen(cdpath) == 0) { sprintf(cdpath, ".%s", DIRSEP); tmp_str = cdpath + strlen(cdpath)+1; *tmp_str = '/0'; } strcpy(tmpfname, cdpath); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname); }//.........这里部分代码省略.........
开发者ID:ionbladez,项目名称:ohboy-zipit,代码行数:101,
示例21: mat2fits// / Converts a matrix composed of complex numbers into a FITS filevoid mat2fits(Matrix < Complex > &m, char *filename) // TBD: fix row major vs colum major{ int status = 0; fitsfile *fptr; long fpixel = 1, naxis = 2, nelements; long naxes[2]; // Initialise storage naxes[0] = (long)m.GetRows(); naxes[1] = (long)m.GetCols(); nelements = naxes[0] * naxes[1]; // Filenames char fitsreal[100]; char fitsimag[100]; for (int i = 0; i < 100; i++) { fitsreal[i] = '/0'; fitsimag[i] = '/0'; } strcpy(fitsreal, filename); strcpy(fitsimag, filename); strcat(fitsreal, "_r"); strcat(fitsimag, "_i"); double *ptrimgreal = (double *)malloc(nelements * sizeof(double)); for (int ii = 0; ii < naxes[0]; ii++) for (int jj = 0; jj < naxes[1]; jj++) ptrimgreal[ii + jj * naxes[0]] = m[naxes[0] - ii - 1][jj].real(); // Create new file, write image, then close file if (status == 0) fits_create_file(&fptr, fitsreal, &status); if (status == 0) fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); if (status == 0) fits_write_img(fptr, TDOUBLE, fpixel, nelements, &ptrimgreal[0], &status); if (status == 0) fits_close_file(fptr, &status); free(ptrimgreal); double *ptrimgimag = (double *)malloc(nelements * sizeof(double)); for (int ii = 0; ii < naxes[0]; ii++) for (int jj = 0; jj < naxes[1]; jj++) ptrimgimag[ii + jj * naxes[0]] = m[ii][jj].imag(); // Create new file, write image, then close file if (status == 0) fits_create_file(&fptr, fitsimag, &status); if (status == 0) fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); if (status == 0) fits_write_img(fptr, TDOUBLE, fpixel, nelements, &ptrimgimag[0], &status); if (status == 0) fits_close_file(fptr, &status); free(ptrimgimag); fits_report_error(stderr, status);}
开发者ID:bkloppenborg,项目名称:oifits-sim,代码行数:73,
示例22: menu_stateint menu_state(int save){ char **statebody=NULL; char* name; int i, flags,ret, del=0,l;#ifndef OHBOY_FILE_STAT_NOT_AVAILABLE /* Not all platforms implement stat()/fstat() */ struct stat fstat; time_t time; char *tstr;#endif char *savedir; char *savename; char *saveprefix; FILE *f; int sizeof_slots=0; while (slots[sizeof_slots] != NULL) sizeof_slots++; statebody = malloc(sizeof_slots * sizeof(char*)); /* FIXME check for NULL return from malloc */ savedir = rc_getstr("savedir"); savename = rc_getstr("savename"); saveprefix = malloc(strlen(savedir) + strlen(savename) + 2); sprintf(saveprefix, "%s%s%s", savedir, DIRSEP, savename); dialog_begin(save?"Save State":"Load State",rom.name); for(i=0; i<sizeof_slots; i++){ name = malloc(strlen(saveprefix) + 5); sprintf(name, "%s.%03d", saveprefix, i);#ifndef OHBOY_FILE_STAT_NOT_AVAILABLE /* if the file exists lookup the timestamp */ if(!stat(name,&fstat)){ time = fstat.st_mtime; tstr = ctime(&time); l = strlen(tstr); statebody[i] = malloc(l); strcpy(statebody[i],tstr); statebody[i][l-1]=0;#else /* check if the file exists */ if(f=fopen(name,"rb")){ fclose(f); statebody[i] = (char*)not_emptyslot;#endif /* OHBOY_FILE_STAT_NOT_AVAILABLE */ flags = FIELD_SELECTABLE; } else { statebody[i] = (char*)emptyslot; flags = save ? FIELD_SELECTABLE : 0; } dialog_text(slots[i],statebody[i],flags); free(name); } if(ret=dialog_end()){ name = malloc(strlen(saveprefix) + 5); sprintf(name, "%s.%03d", saveprefix, ret-1); if(save){ if(f=fopen(name,"wb")){ savestate(f); fclose(f); } }else{ if(f=fopen(name,"rb")){ loadstate(f); fclose(f); vram_dirty(); pal_dirty(); sound_dirty(); mem_updatemap(); } } free(name); } for(i=0; i<sizeof_slots; i++) if(statebody[i] != emptyslot && statebody[i] != not_emptyslot) free(statebody[i]); free(saveprefix); return ret;}#define GBPAL_COUNT 27struct pal_s{ char name[16]; unsigned int dmg_bgp[4]; unsigned int dmg_wndp[4]; unsigned int dmg_obp0[4]; unsigned int dmg_obp1[4];}gbpal[GBPAL_COUNT] = { { .name = "Default", .dmg_bgp = {0X98D0E0,0X68A0B0,0X60707C,0X2C3C3C}, .dmg_wndp = {0X98D0E0,0X68A0B0,0X60707C,0X2C3C3C},//.........这里部分代码省略.........
开发者ID:ionbladez,项目名称:ohboy-zipit,代码行数:101,
示例23: mainintmain( int argc, char *argv[]){ extern int optind; extern int opterr; extern char *optarg; int c; FILE *fp;#ifdef __hpux setlocale(LC_CTYPE,"");#endif #ifdef MDEBUG malloc_debug(2) ; /* helps find malloc/free errors on Sun */#endif /* MDEBUG */ opterr = 1; /* print error message if bad option */ progname = ubasename(argv[0]); cdlname = "-"; c_flag = 0; fortran_flag = 0; netcdf_flag = 0; cmode_modifier = 0; nofill_flag = 0;#if _CRAYMPP && 0 /* initialize CRAY MPP parallel-I/O library */ (void) par_io_init(32, 32);#endif while ((c = getopt(argc, argv, "bcfk:l:no:v:x")) != EOF) switch(c) { case 'c': /* for c output, old version of "-lc" */ c_flag = 1; break; case 'f': /* for fortran output, old version of "-lf" */ fortran_flag = 1; break; case 'b': /* for binary netcdf output, ".nc" extension */ netcdf_flag = 1; break; case 'l': /* specify language, instead of using -c or -f */ { char *lang_name = (char *) emalloc(strlen(optarg)+1); if (! lang_name) { derror ("%s: out of memory", progname); return(1); } (void)strcpy(lang_name, optarg); if (strcmp(lang_name, "c") == 0 || strcmp(lang_name, "C") == 0) { c_flag = 1; } else if (strcmp(lang_name, "f77") == 0 || strcmp(lang_name, "fortran77") == 0 || strcmp(lang_name, "Fortran77") == 0) { fortran_flag = 1; } else { /* Fortran90, Java, C++, Perl, Python, Ruby, ... */ derror("%s: output language %s not implemented", progname, lang_name); return(1); } } break; case 'n': /* old version of -b, uses ".cdf" extension */ netcdf_flag = -1; break; case 'o': /* to explicitly specify output name */ netcdf_flag = 1; netcdf_name = (char *) emalloc(strlen(optarg)+1); if (! netcdf_name) { derror ("%s: out of memory", progname); return(1); } (void)strcpy(netcdf_name,optarg); break; case 'x': /* set nofill mode to speed up creation of large files */ nofill_flag = 1; break; case 'v': /* a deprecated alias for "kind" option */ /*FALLTHRU*/ case 'k': /* for specifying variant of netCDF format to be generated */ { char *kind_name = (char *) emalloc(strlen(optarg)+1); if (! kind_name) { derror ("%s: out of memory", progname); return(1); } (void)strcpy(kind_name, optarg); /* The default kind is kind 1, with 32-bit offsets */ if (strcmp(kind_name, "1") == 0 || strcmp(kind_name, "classic") == 0) { cmode_modifier = 0; } /* The 64-bit offset kind (2) should only be used if actually needed */ else if (strcmp(kind_name, "2") == 0 || strcmp(kind_name, "64-bit-offset") == 0) {//.........这里部分代码省略.........
开发者ID:zhangxiaoyu11,项目名称:mAMBER,代码行数:101,
示例24: menu_browsedirchar* menu_browsedir(char* fpathname, char* file, char *title, char *exts){ /* this routine has side effects with fpathname and file, FIXME */ DIR *dir; struct dirent *d; int n=0, i, j; char *files[1<<16]; /* 256Kb */#ifndef DT_DIR struct stat s; char tmpfname[PATH_MAX]; char *tmpfname_end;#endif /* DT_DIR */ if(!(dir = opendir(fpathname))) return NULL; /* FIXME try parent(s) until out of paths */ /* TODO FIXME add root directory check (to avoid adding .. as a menu option when at "/" or "x:/") */ files[n] = malloc(4); strcpy(files[n], ".."); strcat(files[n], DIRSEP); n++; d = readdir(dir); if(d && !strcmp(d->d_name,".")) d = readdir(dir); if(d && !strcmp(d->d_name,"..")) d = readdir(dir);#ifndef DT_DIR strcpy(tmpfname, fpathname); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname);#endif /* DT_DIR */ while(d){#ifndef DT_DIR /* can not lookup type from search result have to stat filename*/ strcpy(tmpfname_end, d->d_name); stat(tmpfname, &s); if(S_ISDIR (s.st_mode))#else if ((d->d_type & DT_DIR) == DT_DIR)#endif /* DT_DIR */ { files[n] = malloc(strlen(d->d_name)+2); strcpy(files[n], d->d_name); strcat(files[n], DIRSEP); n++; } else if(filterfile(d->d_name,exts)){ files[n] = malloc(strlen(d->d_name)+1); strcpy(files[n], d->d_name); n++; } d = readdir(dir); } closedir (dir); qsort(files+1,n-1,sizeof(char*),fcompare); dialog_begin(title, fpathname); for(i=0; i<n; i++){ dialog_text(files[i],"",FIELD_SELECTABLE); } if(j = dialog_end()){ if(file) { strcpy(file,files[j-1]); } else { file = files[j-1]; files[j-1] = NULL; } } for(i=0; i<n; i++){ free(files[i]); } return j ? file : NULL;}
开发者ID:ionbladez,项目名称:ohboy-zipit,代码行数:77,
示例25: SQLSetConfigModechar *__find_lib_name( char *dsn, char *lib_name, char *driver_name ){ char driver[ INI_MAX_PROPERTY_VALUE + 1 ]; char driver_lib[ INI_MAX_PROPERTY_VALUE + 1 ]; SQLSetConfigMode( ODBC_USER_DSN ); /* * GET DRIVER FROM ODBC.INI */ SQLGetPrivateProfileString( dsn, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBC.INI" ); if ( driver_lib[ 0 ] == 0 ) { /* * if not found look in system DSN */ SQLSetConfigMode( ODBC_SYSTEM_DSN ); SQLGetPrivateProfileString( dsn, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBC.INI" ); SQLSetConfigMode( ODBC_BOTH_DSN ); if ( driver_lib[ 0 ] == 0 ) return NULL; } /* * GET DRIVER FROM ODBCINST.INI IF ODBC.INI HAD USER FRIENDLY NAME */ strcpy( driver_name, "" ); if ( driver_lib[ 0 ] != '/' ) { strcpy( driver, driver_lib ); /* * allow the use of "User odbcinst files */#ifdef PLATFORM64 SQLGetPrivateProfileString( driver, "Driver64", "", driver_lib, sizeof( driver_lib ), "ODBCINST.INI" ); if ( driver_lib[ 0 ] == '/0' ) { SQLGetPrivateProfileString( driver, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBCINST.INI" ); }#else SQLGetPrivateProfileString( driver, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBCINST.INI" );#endif strcpy( driver_name, driver ); if ( driver_lib[ 0 ] == 0 ) { return NULL; } } strcpy( lib_name, driver_lib ); return lib_name;}
开发者ID:capensis,项目名称:canopsis-edc,代码行数:69,
示例26: lfm_format_uri// subm is submission idx, or -1 for nowplaying// returns number of bytes added, or -1static intlfm_format_uri (int subm, DB_playItem_t *song, char *out, int outl, time_t started_timestamp, float playtime) { if (subm > 50) { trace ("lastfm: it's only allowed to send up to 50 submissions at once (got idx=%d)/n", subm); return -1; } int sz = outl; char a[META_FIELD_SIZE]; // artist char t[META_FIELD_SIZE]; // title char b[META_FIELD_SIZE]; // album float l; // duration char n[META_FIELD_SIZE]; // tracknum char m[META_FIELD_SIZE]; // muzicbrainz id char ka[6] = "a"; char kt[6] = "t"; char kb[6] = "b"; char kl[6] = "l"; char kn[6] = "n"; char km[6] = "m"; if (subm >= 0) { snprintf (ka+1, 5, "[%d]", subm); strcpy (kt+1, ka+1); strcpy (kb+1, ka+1); strcpy (kl+1, ka+1); strcpy (kn+1, ka+1); strcpy (km+1, ka+1); } if (lfm_fetch_song_info (song, playtime, a, t, b, &l, n, m) == 0) {// trace ("playtime: %f/nartist: %s/ntitle: %s/nalbum: %s/nduration: %f/ntracknum: %s/n---/n", song->playtime, a, t, b, l, n); } else {// trace ("file %s doesn't have enough tags to submit to last.fm/n", song->fname); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, ka, a) < 0) {// trace ("failed to add %s=%s/n", ka, a); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, kt, t) < 0) {// trace ("failed to add %s=%s/n", kt, t); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, kb, b) < 0) {// trace ("failed to add %s=%s/n", kb, b); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, kn, n) < 0) {// trace ("failed to add %s=%s/n", kn, n); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, km, m) < 0) {// trace ("failed to add %s=%s/n", km, m); return -1; } int processed; processed = snprintf (out, outl, "%s=%d&", kl, (int)l); if (processed > outl) {// trace ("failed to add %s=%d/n", kl, (int)l); return -1; } out += processed; outl -= processed; if (subm >= 0) { processed = snprintf (out, outl, "i[%d]=%d&o[%d]=P&r[%d]=&", subm, (int)started_timestamp, subm, subm); if (processed > outl) {// trace ("failed to add i[%d]=%d&o[%d]=P&r[%d]=&/n", subm, (int)song->started_timestamp, subm, subm); return -1; } out += processed; outl -= processed; } return sz - outl;}
开发者ID:popoffka,项目名称:deadbeef,代码行数:80,
示例27: hashCreate/**************************************************************** hashCreate - Creates an empty hash table*** This routine creates am empty hash table of size <size> * and initializes it. Memory for the buffer is allocated from * the system memory partition.*** RETURNS:* ID of the hash table , or NULL if memory cannot be allocated.** Author Greg Brissey 8/5/93*/HASH_ID hashCreate(int size,PFL hashf, PFI cmpf, char* idstr)/* int size; size of hash table *//* PFL hashf; pointer to user defined hashing function *//* PFI cmpf; pointer to user defined comparison function *//* char* idstr; Identifing string for user */{ HASH_ID pHashTbl; HASH_ENTRY *pHashAry; register long i; char tmpstr[80]; pHashTbl = (HASH_ID) malloc(sizeof(HASH_TABLE)); /* create structure */ if (pHashTbl == NULL) return (NULL); if (idstr == NULL) { sprintf(tmpstr,"%s %d/n",HashIDStr,++HIdCnt); pHashTbl->pHashIdStr = (char *) malloc(strlen(tmpstr)+2); } else { pHashTbl->pHashIdStr = (char *) malloc(strlen(idstr)+2); } if (pHashTbl->pHashIdStr == NULL) { free(pHashTbl); return(NULL); } if (idstr == NULL) { strcpy(pHashTbl->pHashIdStr,tmpstr); } else { strcpy(pHashTbl->pHashIdStr,idstr); } /* create space for all table entries */ pHashTbl->pHashEntries = (HASH_ENTRY *) malloc( (size * sizeof(HASH_ENTRY)) ); if (pHashTbl->pHashEntries == NULL) { free(pHashTbl->pHashIdStr); free(pHashTbl); return (NULL); } pHashTbl->numEntries =(long) 0; pHashTbl->maxEntries = size; pHashTbl->collisions = (long) 0; if (hashf == NULL) pHashTbl->pHashFunc = strhash; /* if users func is NULL use default hash */ else pHashTbl->pHashFunc = hashf; /* set up users hash function */ if (cmpf == NULL) pHashTbl->pCmpFunc = cmpstrs; /* if users func is NULL use default hash */ else pHashTbl->pCmpFunc = cmpf; /* set up users hash function */ pHashAry = pHashTbl->pHashEntries; /* initialize hash table */ for(i=0;i<size;i++) { pHashAry[i].hashKey = NULL; pHashAry[i].refAddr= NULL; } return( pHashTbl );}
开发者ID:DanIverson,项目名称:OpenVnmrJ,代码行数:91,
示例28: auth_v2intauth_v2 (void) { if (lfm_sess[0]) { return 0; } char msg[4096]; char sigstr[4096]; uint8_t sig[16]; snprintf (sigstr, sizeof (sigstr), "api_key%smethodauth.getToken%s", LASTFM_API_KEY, LASTFM_API_SECRET); deadbeef->md5 (sig, sigstr, strlen (sigstr)); deadbeef->md5_to_str (sigstr, sig); snprintf (msg, sizeof (msg), "%s/?api_key=%s&method=auth.getToken&api_sig=%s", SCROBBLER_URL, LASTFM_API_KEY, sigstr); // get token char lfm_token[33] = ""; int status = curl_req_send (msg, NULL); if (!status) { // parse output if (strstr (lfm_reply, "<lfm status=/"ok/">")) { char *token = strstr (lfm_reply, "<token>"); if (token) { token += 7; char *end = strstr (token, "</token>"); if (end) { *end = 0; snprintf (msg, sizeof (msg), "http://www.last.fm/api/auth/?api_key=%s&token=%s", LASTFM_API_KEY, token); trace ("Dear user. Please visit this URL and authenticate deadbeef. Thanks./n"); trace ("%s/n", msg); strncpy (lfm_token, token, 32); lfm_token[32] = 0; } } } } curl_req_cleanup (); if (!lfm_token[0]) { // total fail, give up return -1; } // get session snprintf (sigstr, sizeof (sigstr), "api_key%smethodauth.getSessiontoken%s%s", LASTFM_API_KEY, lfm_token, LASTFM_API_SECRET); deadbeef->md5 (sig, sigstr, strlen (sigstr)); deadbeef->md5_to_str (sigstr, sig); snprintf (msg, sizeof (msg), "method=auth.getSession&token=%s&api_key=%s&api_sig=%s", lfm_token, LASTFM_API_KEY, sigstr); for (;;) { status = curl_req_send (SCROBBLER_URL, msg); if (!status) { char *sess = strstr (lfm_reply, "<key>"); if (sess) { sess += 5; char *end = strstr (sess, "</key>"); if (end) { *end = 0; char config[1024]; snprintf (config, sizeof (config), "%s/.config/deadbeef/lastfmv2", getenv ("HOME")); trace ("got session key %s/n", sess); FILE *fp = fopen (config, "w+b"); if (!fp) { trace ("lastfm: failed to write config file %s/n", config); curl_req_cleanup (); return -1; } if (fwrite (sess, 1, 32, fp) != 32) { fclose (fp); trace ("lastfm: failed to write config file %s/n", config); curl_req_cleanup (); return -1; } fclose (fp); strcpy (lfm_sess, sess); } }// trace ("reply: %s/n", lfm_reply); } curl_req_cleanup (); if (lfm_sess[0]) { break; } sleep (5); } return 0;}
开发者ID:popoffka,项目名称:deadbeef,代码行数:82,
示例29: slogistatic void *do_resolve(void *hostname){ slogi("do_resolve hostname[%s]",hostname); #if 0 /*[/home/st/toffaletti/armhf/key.c_114__st_thread_cleanup]key [110876] key_max[0]do_resolve hostname[www.baidu.com]after strcpy strcpy(host,hostname)[www.baidu.com] hostname[www.baidu.com][/home/st/toffaletti/armhf/event.c_421__st_select_fd_new]_st_select_fd_new osfd[7] ok[/home/st/toffaletti/armhf/io.c_749_st_sendto]sendto get n [31][/home/st/toffaletti/armhf/io.c_730_st_recvfrom]recvfrom get n [90][/home/st/toffaletti/armhf/examples/res.c_278_dns_getaddr]query_domain return 0[/home/st/toffaletti/armhf/io.c_212_st_netfd_close]JUST TEST st_netfd_closeProgram received signal SIGSEGV, Segmentation fault.0x00000000 in ?? ()(gdb) bt#0 0x00000000 in ?? ()#1 0x0000b06e in dns_getaddr ( host=<error reading variable: Cannot access memory at address 0xc>, addr=<error reading variable: Cannot access memory at address 0x8>, timeout=<error reading variable: Cannot access memory at address 0x0>) at /home/st/toffaletti/armhf/examples/res.c:281Backtrace stopped: previous frame inner to this frame (corrupt stack?)(gdb) */ char host[128]; memset(host,0,128); //strcpy(host,hostname); slogi("after strcpy strcpy(host,hostname)[%s] hostname[%s]",strcpy(host,hostname),hostname); #else char *host=malloc(128); memset(host,0,128); slogi("sizeof(hostname)[%d] strlen(hostname)[%d]",sizeof(hostname),strlen(hostname)); memcpy(host,hostname,strlen(hostname)+1); slogi("host is [%s]",host); #endif struct in_addr addr;#if 1 /* Use dns_getaddr() instead of gethostbyname(3) to get IP address */ #if 1 int ret=-99; dns_getaddr(host, &addr, TIMEOUT); LOGD("dns_getaddr RET"); if ( ret< 0) { #else if ( dns_getaddr(host, &addr, TIMEOUT)< 0) { #endif// #endif /*PC C++ strcpyW函数代码示例 C++ strcopy函数代码示例
|