• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ readline函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中readline函数的典型用法代码示例。如果您正苦于以下问题:C++ readline函数的具体用法?C++ readline怎么用?C++ readline使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了readline函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: read_command

//return value: number of parameters
//0 represents only command without any parameters
//-1 represents wrong input
int read_command(char **command,char **parameters,char *prompt)
{
#ifdef READLINE_ON
    char* tmpbuffer = buffer
    buffer  = readline(prompt);
    if(feof(stdin) == 0)
    {
        printf("\n");
        exit(0);
    }
#else
    printf("%s",prompt);
    char* Res_fgets = fgets(buffer,MAXLINE,stdin);
    if(Res_fgets == NULL)
    {
        printf("\n");
        exit(0);
    }		
#endif
    if(buffer[0] == '\0')
        return -1;
    char *pStart,*pEnd;
    int count = 0;
    int isFinished = 0;
    pStart = pEnd = buffer;
    while(isFinished == 0)
    {
        while((*pEnd == ' ' && *pStart == ' ') || (*pEnd == '\t' && *pStart == '\t'))
        {
            pStart++;
            pEnd++;
        }

        if(*pEnd == '\0' || *pEnd == '\n')
        {
            if(count == 0)
                return -1;
            break;
        }

        while(*pEnd != ' ' && *pEnd != '\0' && *pEnd != '\n')
            pEnd++;


        if(count == 0)
        {
            char *p = pEnd;
            *command = pStart;
            while(p!=pStart && *p !='/')
                p--;
            if(*p == '/')
                p++;
            //else //p==pStart
            parameters[0] = p;
            count += 2;
#ifdef DEBUG
            printf("\ncommand:  %s\n",*command);
#endif
        }
        else if(count <= MAXARG)
        {
            parameters[count-1] = pStart;
            count++;
        }
        else
        {
            break;
        }

        if(*pEnd == '\0' || *pEnd == '\n')
        {
            *pEnd = '\0';
            isFinished = 1;
        }
        else
        {
            *pEnd = '\0';
            pEnd++;
			pStart = pEnd;
        }
    }

    parameters[count-1] = NULL;

#ifdef DEBUG
    /*input analysis*/
    printf("input analysis:\n");
    printf("pathname:%s\ncommand:%s\nparameters:\n",*command,parameters[0]);
    int i;
    for(i=0;i<count-1;i++)
        printf("%s\n",parameters[i]);
#endif

//free the space of readline() ---error
/**
 * edit by reeves 
 * 2015/07/03
//.........这里部分代码省略.........
开发者ID:reeves55,项目名称:wshell,代码行数:101,代码来源:read_command.c


示例2: gridread


//.........这里部分代码省略.........
      }

      /*
      Free row buffer                                         (13)
      */
      CFree1 ((char *)rowbuf);
      /*
      Close handles                                           (14)
      */
      CellLyrClose(channel1);
      /*
      Done with the library                                   (15)
      */
      GridIOExit();
      return(0);
    }

/*  Here assume file is ASCII  Close ESRI stuff. */
//    CellLyrClose(channel1);
  GridIOExit();

  *filetype=0;
  fp = fopen(file,"r");
  printf("%s\n",file);
  if(fp == NULL)
  {
    printf("\nERROR: Cannot open input file (%s).\n\n",file);
    return(1);
  }

  /* read ARC-Info header */
  while(1)
  {
    readline(fp, fline);
    if(!isalpha(*fline) || *fline == '-')
      break;

    hdrlines++;

    sscanf(fline,"%s %f",keyword,&value);

    if(strcmp(keyword,"ncols") == 0 || strcmp(keyword,"NCOLS") == 0)
      *nx = (int)value;
    else if(strcmp(keyword,"nrows") == 0 || strcmp(keyword,"NROWS") == 0)
      *ny = (int)value;
    else if(strcmp(keyword,"xllcenter") == 0 || strcmp(keyword,"XLLCENTER") == 0)
    {
      utmetag = 'c';
      utme = value;
    }
    else if(strcmp(keyword,"xllcorner") == 0 || strcmp(keyword,"XLLCORNER") == 0)
    {
      utmetag = 'e';
      utme = value;
    }
    else if(strcmp(keyword,"yllcenter") == 0 || strcmp(keyword,"YLLCENTER") == 0)
    {
      utmntag = 'c';
      utmn = value;
    }
    else if(strcmp(keyword,"yllcorner") == 0 || strcmp(keyword,"YLLCORNER") == 0)
    {
      utmntag = 'e';
      utmn = value;
    }
    else if(strcmp(keyword,"cellsize") == 0 || strcmp(keyword,"CELLSIZE") == 0)
开发者ID:mlt,项目名称:PIHM,代码行数:67,代码来源:gridio.cpp


示例3: do_askenv

int do_askenv ( cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	extern char console_buffer[CFG_CBSIZE];
	char message[CFG_CBSIZE];
	int size = CFG_CBSIZE - 1;
	int len;
	char *local_args[4];

	local_args[0] = argv[0];
	local_args[1] = argv[1];
	local_args[2] = NULL;
	local_args[3] = NULL;

	if (argc < 2) {
		printf ("Usage:\n%s\n", cmdtp->usage);
		return 1;
	}
	/* Check the syntax */
	switch (argc) {
	case 1:
		printf ("Usage:\n%s\n", cmdtp->usage);
		return 1;

	case 2:		/* askenv envname */
		sprintf (message, "Please enter '%s':", argv[1]);
		break;

	case 3:		/* askenv envname size */
		sprintf (message, "Please enter '%s':", argv[1]);
		size = simple_strtoul (argv[2], NULL, 10);
		break;

	default:	/* askenv envname message1 ... messagen size */
	    {
		int i;
		int pos = 0;

		for (i = 2; i < argc - 1; i++) {
			if (pos) {
				message[pos++] = ' ';
			}
			strcpy (message+pos, argv[i]);
			pos += strlen(argv[i]);
		}
		message[pos] = '\0';
		size = simple_strtoul (argv[argc - 1], NULL, 10);
	    }
		break;
	}

	if (size >= CFG_CBSIZE)
		size = CFG_CBSIZE - 1;

	if (size <= 0)
		return 1;

	/* prompt for input */
	len = readline (message);

	if (size < len)
		console_buffer[size] = '\0';

	len = 2;
	if (console_buffer[0] != '\0') {
		local_args[2] = console_buffer;
		len = 3;
	}

	/* Continue calling setenv code */
	return _do_setenv (flag, len, local_args);
}
开发者ID:8devices,项目名称:Caraboot,代码行数:71,代码来源:cmd_nvedit.c


示例4: main

int
main(int argc, char **argv)
{
  char ruby_code[1024] = { 0 };
  char last_code_line[1024] = { 0 };
#ifndef ENABLE_READLINE
  int last_char;
  int char_index;
#else
  char *home = NULL;
#endif
  mrbc_context *cxt;
  struct mrb_parser_state *parser;
  mrb_state *mrb;
  mrb_value result;
  struct _args args;
  int n;
  int code_block_open = FALSE;
  int ai;

  /* new interpreter instance */
  mrb = mrb_open();
  if (mrb == NULL) {
    fputs("Invalid mrb interpreter, exiting mirb\n", stderr);
    return EXIT_FAILURE;
  }
  mrb_define_global_const(mrb, "ARGV", mrb_ary_new_capa(mrb, 0));

  n = parse_args(mrb, argc, argv, &args);
  if (n == EXIT_FAILURE) {
    cleanup(mrb, &args);
    usage(argv[0]);
    return n;
  }

  print_hint();

  cxt = mrbc_context_new(mrb);
  cxt->capture_errors = 1;
  cxt->lineno = 1;
  mrbc_filename(mrb, cxt, "(mirb)");
  if (args.verbose) cxt->dump_result = 1;

  ai = mrb_gc_arena_save(mrb);

#ifdef ENABLE_READLINE
  using_history();
  home = getenv("HOME");
#ifdef _WIN32
  if (!home)
    home = getenv("USERPROFILE");
#endif
  if (home) {
    strcpy(history_path, home);
    strcat(history_path, "/");
    strcat(history_path, history_file_name);
    read_history(history_path);
  }
#endif


  while (TRUE) {
#ifndef ENABLE_READLINE
    print_cmdline(code_block_open);

    char_index = 0;
    while ((last_char = getchar()) != '\n') {
      if (last_char == EOF) break;
      last_code_line[char_index++] = last_char;
    }
    if (last_char == EOF) {
      fputs("\n", stdout);
      break;
    }

    last_code_line[char_index] = '\0';
#else
    char* line = readline(code_block_open ? "* " : "> ");
    if (line == NULL) {
      printf("\n");
      break;
    }
    strncpy(last_code_line, line, sizeof(last_code_line)-1);
    add_history(line);
    free(line);
#endif

    if ((strcmp(last_code_line, "quit") == 0) || (strcmp(last_code_line, "exit") == 0)) {
      if (!code_block_open) {
        break;
      }
      else{
        /* count the quit/exit commands as strings if in a quote block */
        strcat(ruby_code, "\n");
        strcat(ruby_code, last_code_line);
      }
    }
    else {
      if (code_block_open) {
        strcat(ruby_code, "\n");
//.........这里部分代码省略.........
开发者ID:FikiHafana,项目名称:ArangoDB,代码行数:101,代码来源:mirb.c


示例5: filemenu

void filemenu(int mode)
{
	getstats(mode);
	if (button(100,100,170,120,"OPTIMIZE",9,13,base2,false,mode)==DDgui_LeftClick && mode!=DD_AfterCheck) { optimizeproject(); waitleftbutton=true; }
	if (button(100,121,170,141,"TextureO",9,13,base2,false,mode)==DDgui_LeftClick && mode!=DD_AfterCheck) { savetextureusefile(); waitleftbutton=true; }
	if (mode==DD_Draw)
	{
		glColor4f(buttontextlit);
		rectangle(661,120,775,264);
	}	  
	if (mode==DD_Check)
		if (leftclickinwindow(661,121,774,263) && mouseinwindow(661,121,774,260)) fscnselected=min(fscnbarpos+(my-121) / 10,filenum(prjlist)-1);
	if ((mode ==DD_Check) && mouseinwindow(661,121,774,263)) fscnbarpos-=wheel*4;
	scroller(775,120,790,264,15,15,filenum(prjlist),14,fscnbarpos,mode);
	if (mode==DD_Draw)
	{
		pf = prjlist;
		for (x=1;x<=fscnbarpos;x++) pf=pf->next;
		for (x=0;x<=13;x++)
		{
			if (pf!=NULL)
			{
				if (fscnbarpos+x==fscnselected) glColor4f(col4); else glColor4f(buttontextlit);
				glRasterPos2i(665,130+x*10);
				strcpy(st,pf->filedata.cFileName);
				glPrint(st,base2,18);
				pf=pf->next;
			}
		}

		glColor4f(buttontextlit);
		sprintf(s,"%d PROJECTS.",filenum(prjlist));
		glRasterPos2i(683,277);
		glPrint(s,base2);

	}
	glColor4f(1,1,1,1);
	if ((button(686,283,771,299,texbutton1,0,96.0/256.0,85.0/256.0,112.0/256.0,false,mode) == DDgui_LeftClick) && (mode!=DD_AfterCheck))
	{
		pf = prjlist;
		for (x=1;x<=fscnselected;x++) pf=pf->next;
		//sprintf(s,"%s%s",scenedir,pf->filedata.cFileName);
		memset(lastfilename,0,256);
		memcpy(lastfilename,pf->filedata.cFileName,strlen(pf->filedata.cFileName)-4);
		sprintf(s,"%s%s",projectdir,pf->filedata.cFileName);
		//loadaDDictscene(*actualscene,NULL,s,true,true,true,true,true);				
		LoadProject(s);
		modellviews[3].cam=actualscene->editview;
		modellviews[3].cam2=actualscene->editview;
		tTexture *tex=texturelist;
		while ((tex!=NULL) && (tex->number!=selectedtexture)) tex=tex->next;
		memcpy(generatedtexture.commands,tex->commands,sizeof(generatedtexture.commands));
		memcpy(generatedtexture.texts,tex->texts,sizeof(generatedtexture.texts));
		generatedtexture.commandnum=tex->commandnum;
		//memcpy(generatedtexture.layers,tex->layers,sizeof(generatedtexture.layers));
		for (y=0;y<=3;y++)
		{
			glBindTexture(GL_TEXTURE_2D, texlayers[y]);
			glTexImage2D(GL_TEXTURE_2D,0,3,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,generatedtexture.layers[y]);
		}				
		
		if (materiallist!=NULL)
		{
			matselected=0;
			material *mat=materiallist;
			for (x=1;x<=matselected;x++) mat=mat->next;
			mattexture=mat->handle;
		}				

		waitleftbutton=true;
	}

	if (button(685,300,770,316,texbutton1,0,144.0/256.0,85.0/256.0,160.0/256.0,false,mode) == DDgui_LeftClick) 
	{
		char *ss=readline("Enter Filename (.scn not needed)",210,0,base2,lastfilename);
		if (ss!="")
		{
			//sprintf(s,"%s%s.scn",scenedir,ss);
			//saveaDDictscene(*actualscene,NULL,s,scntexturesave, scncamerasave, scnselectionsave, scnlightsave, scnobjectsave);
			memset(lastfilename,0,256);
			memcpy(lastfilename,ss,strlen(ss));
			sprintf(s,"%s%s.64k",projectdir,ss);
			SaveProject(s);
		}
	}
	if (button(685,317,770,333,texbutton1,0,160.0/256.0,85.0/256.0,176.0/256.0,false,mode) == DDgui_LeftClick) 
	{
		char *ss=readline("Enter Filename (.scn not needed)",210,0,base2,"");
		if (ss!="")
		{
			sprintf(s,"%s%s.m64",minimaldir,ss);
			//SaveMinimalScene(*actualscene,NULL,s);
			saveminimalproject(s,2);
		}
	}
	/*RadioButton(681,341,scntexturesave,"TEXTURES",mode);
	RadioButton(681,355,scncamerasave,"CAMERAS",mode);
	RadioButton(681,369,scnselectionsave,"SELECTIONS",mode);
	RadioButton(681,383,scnlightsave,"LIGHTS",mode);
	RadioButton(681,397,scnobjectsave,"OBJECTS",mode);*/
//.........这里部分代码省略.........
开发者ID:ConspiracyHu,项目名称:2012SourcePack,代码行数:101,代码来源:filemenu.cpp


示例6: printf

void *CLInterface(void *data)
{
    printf(RED_BEGIN"#Ready to operation ('h' for help)#\n"COLOR_END);

    (void)data;
    OCStackResult ret;
    char query[MAX_LINE] = {0,};
    const char prompt[] = BOLD_BEGIN"IoTivity-DP#"COLOR_END" ";
    const char* helpmsg[6] = {
            GREEN_BEGIN"# h  (or help) : show help message"COLOR_END,
            GREEN_BEGIN"# dd (DP device discovery) : discover Direct-Pairing devices"COLOR_END,
            GREEN_BEGIN"# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing"COLOR_END,
            GREEN_BEGIN"# sd (send data) : send data to device"COLOR_END,
            GREEN_BEGIN"# ll (list all device) : list all discovered/paired devices"COLOR_END,
            GREEN_BEGIN"# q  (quit) : quit test"COLOR_END,
        };

    for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)
    {
        fprintf(stderr, "%s\n", helpmsg[i]);
    }
    printf("\n");

    // cli
    for (;;)
    {
        const char *input = readline(prompt, NULL);
        if (!input) {
            continue;
        }

        strncpy(query, input, MAX_LINE);
        if (!strlen(query))
        {
            continue;
        }
        else if (!strcmp(query, "h") || !strcmp(query, "help"))
        {
            for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)
            {
                fprintf(stderr, "%s\n", helpmsg[i]);
            }
            continue;
        }
        else
        {
            if (!strcmp(query, "dd"))
            {
                OIC_LOG(INFO, TAG, "- Direct-Pairing device discovery -");

                ret = DirectPairingDiscovery();
                if (OC_STACK_OK != ret)
                {
                    OIC_LOG(ERROR, TAG, "Error in DirectPairingDiscovery()");
                }
            }
            else if (!strcmp(query, "dp"))
            {
                OIC_LOG(INFO, TAG, "- Negotiate DP method & Start Direct-Pairing -");

                printf("\n   * List of  discovered device\n");
                printList(discoveredDevs);

                // target peer
                OCDPDev_t *peer = NULL;
                long peerIdx;
                input = readline("   > Enter Peer Device Number to initiate Direct-Pairing: ", NULL);
                if (!input || !strlen(input))
                {
                    continue;
                }
                char *ptr;
                peerIdx = strtol(input, &ptr, 10);

                peer = getDev(discoveredDevs, (uint32_t)peerIdx);
                if (NULL == peer)
                {
                    OIC_LOG(ERROR, TAG, "Not found the peer in discovered list");
                    continue;
                }

                // get pairing method
                long pmIdx;
                OCPrm_t pmSel = DP_NOT_ALLOWED;
                if (false == printPairingMethod(peer))
                {
                    OIC_LOG(ERROR, TAG, "Target does not support the Direct-Pairing");
                    continue;
                }
                input = readline("   > Enter pairing method: ", NULL);
                if (!input || !strlen(input))
                {
                    continue;
                }
                pmIdx = strtol(input, &ptr, 10);
                printf("\n");
                if (0 >= pmIdx || peer->prmLen+1 < (size_t)pmIdx)
                {
                    OIC_LOG(ERROR, TAG, "Invalid mode selection");
                    continue;
//.........这里部分代码省略.........
开发者ID:Lyoncore,项目名称:iotivity-simple-client-server-uc16,代码行数:101,代码来源:occlientdirectpairing.cpp


示例7: split

void split(char *input_file, int l, int machines, int nr_query, struct Query_Machine *q_machine, int *query)
{
	int machine_id = 0;
	double y;
	int len = 0;
	FILE *fp = fopen(input_file,"r");
	char *idx, *val, *endptr;
	char *label;
	char **out_file = (char**)malloc(sizeof(char*)*machines);
	for(int i=0;i<machines;i++)
		out_file[i] = (char*)malloc(sizeof(char)*1024);
    FILE **f = (FILE**)malloc(sizeof(FILE*)*machines);
    
    if(mkdir("temp_dir",0777)==0)
    {
        printf("Directory was successfully created!\n");
    }
    else
    {
        printf("Directory has existed!!\n");
    }
    
    for(int i=0;i<machines;i++)
	{
		sprintf(out_file[i],"temp_dir/train.txt.%d",i);
		f[i] = fopen(out_file[i],"w");
	}

	char *copy_line = (char*)malloc(sizeof(char)*2048);
	for(int j=0;j<l;j++)
	{
		readline(fp);		
		len = (int)strlen(line);
		//printf("len=%d for line:%d\n",len,j+1);
		if(len > 2048)
		{
			copy_line = (char*)realloc(copy_line,len*sizeof(char));
		}
		sprintf(copy_line, "%s", line);
		//strcpy(copy_line,line);
		//printf("copy_line:%s",copy_line);
		//printf("line:%s",line);
		label = strtok(line, " \t\n");
		if(label == NULL)
			exit_input_error(j+1);
		y = strtod(label, &endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(j+1);
		idx = strtok(NULL,":");
		val = strtok(NULL, " \t");
		if(val == NULL)
			exit_input_error(j+1);
		if(!strcmp(idx,"qid"))
		{
			errno = 0;
			query[j] = (int)strtol(val, &endptr, 10);
			if(endptr == val || errno !=0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(j+1);
		}

		for(int i=0;i<nr_query;i++)
		{
			if(query[j] == q_machine[i].query)
			{
				machine_id = q_machine[i].machine_id;
				break;
			}
		}
		fprintf(f[machine_id],"%s",copy_line);

	}
	free(copy_line);
	for(int i=0;i<machines;i++)
		free(out_file[i]);
	free(out_file);
	for(int i=0;i<machines;i++)
		fclose(f[i]);
	rewind(fp);
	fclose(fp);
}
开发者ID:jinshubai,项目名称:dlranksvm,代码行数:80,代码来源:split.cpp


示例8: do_repl

STATIC int do_repl(void) {
    mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; "
        MICROPY_PY_SYS_PLATFORM " version\nUse Ctrl-D to exit, Ctrl-E for paste mode\n");

    #if MICROPY_USE_READLINE == 1

    // use MicroPython supplied readline

    vstr_t line;
    vstr_init(&line, 16);
    for (;;) {
        mp_hal_stdio_mode_raw();

    input_restart:
        vstr_reset(&line);
        int ret = readline(&line, ">>> ");
        mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;

        if (ret == CHAR_CTRL_D) {
            // EOF
            printf("\n");
            mp_hal_stdio_mode_orig();
            vstr_clear(&line);
            return 0;
        } else if (ret == CHAR_CTRL_E) {
            // paste mode
            mp_hal_stdout_tx_str("\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\n=== ");
            vstr_reset(&line);
            for (;;) {
                char c = mp_hal_stdin_rx_chr();
                if (c == CHAR_CTRL_C) {
                    // cancel everything
                    mp_hal_stdout_tx_str("\n");
                    goto input_restart;
                } else if (c == CHAR_CTRL_D) {
                    // end of input
                    mp_hal_stdout_tx_str("\n");
                    break;
                } else {
                    // add char to buffer and echo
                    vstr_add_byte(&line, c);
                    if (c == '\r') {
                        mp_hal_stdout_tx_str("\n=== ");
                    } else {
                        mp_hal_stdout_tx_strn(&c, 1);
                    }
                }
            }
            parse_input_kind = MP_PARSE_FILE_INPUT;
        } else if (line.len == 0) {
            if (ret != 0) {
                printf("\n");
            }
            goto input_restart;
        } else {
            // got a line with non-zero length, see if it needs continuing
            while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
                vstr_add_byte(&line, '\n');
                ret = readline(&line, "... ");
                if (ret == CHAR_CTRL_C) {
                    // cancel everything
                    printf("\n");
                    goto input_restart;
                } else if (ret == CHAR_CTRL_D) {
                    // stop entering compound statement
                    break;
                }
            }
        }

        mp_hal_stdio_mode_orig();

        mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line.buf, line.len, false);
        ret = execute_from_lexer(lex, parse_input_kind, true);
        if (ret & FORCED_EXIT) {
            return ret;
        }
    }

    #else

    // use GNU or simple readline

    for (;;) {
        char *line = prompt(">>> ");
        if (line == NULL) {
            // EOF
            return 0;
        }
        while (mp_repl_continue_with_input(line)) {
            char *line2 = prompt("... ");
            if (line2 == NULL) {
                break;
            }
            char *line3 = strjoin(line, '\n', line2);
            free(line);
            free(line2);
            line = line3;
        }

//.........这里部分代码省略.........
开发者ID:ChuckM,项目名称:micropython,代码行数:101,代码来源:main.c


示例9: printf

/// %Thread start
void CliRunnable::run() {
	///- Display the list of available CLI functions then beep
	//sLog->outString("");
#if PLATFORM != PLATFORM_WINDOWS
	rl_attempted_completion_function = cli_completion;
	rl_event_hook = cli_hook_func;
#endif
	if (sConfig->GetBoolDefault("BeepAtStart", true))
		printf("\a"); // \a = Alert

	// print this here the first time
	// later it will be printed after command queue updates
	printf("ArkCORE>");

	///- As long as the World is running (no World::m_stopEvent), get the command line and handle it
	while (!World::IsStopped()) {
		fflush(stdout);

		char *command_str; // = fgets(commandbuf, sizeof(commandbuf), stdin);

#if PLATFORM == PLATFORM_WINDOWS
		char commandbuf[256];
		command_str = fgets(commandbuf, sizeof(commandbuf), stdin);
#else
		command_str = readline("ArkCORE>");
		rl_bind_key('\t', rl_complete);
#endif
		if (command_str != NULL) {
			for (int x = 0; command_str[x]; x++)
				if (command_str[x] == '\r' || command_str[x] == '\n') {
					command_str[x] = 0;
					break;
				}

			if (!*command_str) {
#if PLATFORM == PLATFORM_WINDOWS
				printf("ArkCORE>");
#endif
				continue;
			}

			std::string command;
			if (!consoleToUtf8(command_str, command)) // convert from console encoding to utf8
					{
#if PLATFORM == PLATFORM_WINDOWS
				printf("ArkCORE>");
#endif
				continue;
			}
			fflush(stdout);
			sWorld->QueueCliCommand(
					new CliCommandHolder(NULL, command.c_str(), &utf8print,
							&commandFinished));
#if PLATFORM != PLATFORM_WINDOWS
			add_history(command.c_str());
#endif
		} else if (feof(stdin)) {
			World::StopNow(SHUTDOWN_EXIT_CODE);
		}
	}
}
开发者ID:Bootz,项目名称:DeepshjirRepack,代码行数:62,代码来源:CliRunnable.cpp


示例10: read_problem

// read in a problem (in libsvm format)
void read_problem(const char *filename)
{
	int max_index, inst_max_index, i, max_index_=0;
	long int elements, j;
	FILE *fp = fopen(filename,"r");
	char *endptr;
	char *idx, *val, *label;

	if(fp == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",filename);
		exit(1);
	}

	prob.l = 0;
	elements = 0;
	max_line_len = 1024;
	line = Malloc(char,max_line_len);
	while(readline(fp, 0)!=NULL) 
	{
		char *p = strtok(line," \t"); // label

		// features
		while(1)
		{
			idx = strtok(NULL,":"); 
			p = strtok(NULL," \t");
			if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
				break;
			if((int) strtol(idx,&endptr,10)>max_index_) 
				max_index_ = (int) strtol(idx,&endptr,10); 
			elements++;
		}
		elements++; // for bias term
		prob.l++;
	}
	param.real_dim = max_index_; 
	rewind(fp);

	prob.bias=bias;

	prob.y = Malloc(double,prob.l);
	prob.x = Malloc(struct feature_node *,prob.l);
	x_space = Malloc(struct feature_node,elements+prob.l);

	max_index = 0;
	j=0;
	for(i=0;i<prob.l;i++)
	{
		inst_max_index = 0; // strtol gives 0 if wrong format
		readline(fp, param.real_dim); //sym
		prob.x[i] = &x_space[j];
		label = strtok(line," \t\n");
		if(label == NULL) // empty line
			exit_input_error(i+1);

		prob.y[i] = strtod(label,&endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(i+1);

		while(1)
		{
			idx = strtok(NULL,":");
			val = strtok(NULL," \t");

			if(val == NULL)
				break;

			errno = 0;
			x_space[j].index = (int) strtol(idx,&endptr,10);
			if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
				exit_input_error(i+1);
			else
				inst_max_index = x_space[j].index;

			errno = 0;
			x_space[j].value = strtod(val,&endptr);
			if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(i+1);

			++j;
		}

		if(inst_max_index > max_index)
			max_index = inst_max_index;

		if(prob.bias >= 0)
			x_space[j++].value = prob.bias;

		x_space[j++].index = -1;
	}

	if(prob.bias >= 0)
	{
		prob.n=max_index+1;
		for(i=1;i<prob.l;i++)
			(prob.x[i]-2)->index = prob.n; 
		x_space[j-2].index = prob.n;
	}
//.........这里部分代码省略.........
开发者ID:qmmlib,项目名称:QmmLibrary,代码行数:101,代码来源:train.c


示例11: do_predict

void do_predict(FILE *input, FILE *output)
{
    int total = 0;

    int nr_class=get_nr_class(model_);
    double *prob_estimates=NULL;
    int n;
    int nr_feature=get_nr_feature(model_);
    if(model_->bias>=0)
        n=nr_feature+1;
    else
        n=nr_feature;

    if(!check_probability_model(model_))
    {
        fprintf(stderr, "probability output is only supported for logistic regression\n");
        exit(1);
    }

    prob_estimates = (double *) malloc(nr_class*sizeof(double));

    max_line_len = 1024;
    line = (char *)malloc(max_line_len*sizeof(char));
    int clicks = 0;
    int shows = 0;
    while(readline(input) != NULL)
    {
        int i = 0;
        double target_ctr, predict_ctr;
        char *idx, *val, *endptr;

        int inst_max_index = 0; // strtol gives 0 if wrong format

        char *p = strtok(line," \t\n"); //clicks
        if(p == NULL) // empty line
            exit_input_error(total+1);

        clicks = atoi(p);
        p = strtok(NULL," \t"); // shows
        shows = atoi(p);
        p = strtok(NULL," \t"); // qid:1

        if (shows <=0 || clicks > shows) {
            continue;
        }

        target_ctr = (double)clicks / shows;

        while(1)
        {
            if(i>=max_nr_attr-2)	// need one more for index = -1
            {
                max_nr_attr *= 2;
                x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
            }

            idx = strtok(NULL,":");
            val = strtok(NULL," \t");

            if(val == NULL)
                break;
            errno = 0;
            x[i].index = (int) strtol(idx,&endptr,10);
            if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index)
                exit_input_error(total+1);
            else
                inst_max_index = x[i].index;

            errno = 0;
            x[i].value = strtod(val,&endptr);
            if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
                exit_input_error(total+1);

            // feature indices larger than those in training are not used
            if(x[i].index <= nr_feature)
                ++i;
        }

        if(model_->bias>=0)
        {
            x[i].index = n;
            x[i].value = model_->bias;
            i++;
        }
        x[i].index = -1;

        predict_probability(model_,x,prob_estimates);
        fprintf(output,"%d %d ", clicks, shows);
        predict_ctr = prob_estimates[0];
        fprintf(output," %g\n", predict_ctr);
    }

    info("total:%d\n",total);

    free(prob_estimates);
}
开发者ID:vangogh0318,项目名称:algorithm,代码行数:96,代码来源:predict_ctr.c


示例12: on_load_config

/*
 * load config file
 */
void on_load_config(GtkButton *button, gpointer user_data)
{
	FILE *config = fopen(current_path, "r");
	if (!config)
		dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Error reading config file"));

	/* target */
	gchar target[FILENAME_MAX];
	readline(config, target, FILENAME_MAX - 1);
	gtk_entry_set_text(GTK_ENTRY(targetname), target);
	
	/* debugger */
	gchar debugger[FILENAME_MAX];
	readline(config, debugger, FILENAME_MAX - 1);
	int index = debug_get_module_index(debugger);
	if (-1 == index)
	{
		dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Configuration error: debugger module \'%s\' is not found"), debugger);
		gtk_combo_box_set_active(GTK_COMBO_BOX(cmb_debugger), 0);
	}
	else
		gtk_combo_box_set_active(GTK_COMBO_BOX(cmb_debugger), index);

	/* arguments */
	gchar arguments[FILENAME_MAX];
	readline(config, arguments, FILENAME_MAX - 1);
	GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));
	gtk_text_buffer_set_text(buffer, arguments, -1);
	
	/* breakpoints and environment variables */
	breaks_iterate(removebreak);
	wtree_remove_all();
	
	gboolean wrongbreaks = FALSE;
	gchar line[MAXLINE];
	gtk_list_store_clear(store);
	while (readline(config, line, MAXLINE))
	{
		if (!strcmp(line, BREAKPOINTS_MARKER))
		{
			/* file */
			gchar file[FILENAME_MAX];
			readline(config, file, MAXLINE);
			
			/* line */
			int nline;
			readline(config, line, MAXLINE);
			sscanf(line, "%d", &nline);
			
			/* hitscount */
			int hitscount;
			readline(config, line, MAXLINE);
			sscanf(line, "%d", &hitscount);

			/* condition */
			gchar condition[MAXLINE];
			readline(config, condition, MAXLINE);

			/* enabled */
			gboolean enabled;
			readline(config, line, MAXLINE);
			sscanf(line, "%d", &enabled);
			
			/* check whether file is available */
			struct stat st;
			if(!stat(file, &st))
				breaks_add(file, nline, condition, enabled, hitscount);
			else
				wrongbreaks = TRUE;
		}
		else if (!strcmp(line, ENVIRONMENT_MARKER))
		{
			gchar name[MAXLINE], value[1000];
			readline(config, name, MAXLINE);
			readline(config, value, MAXLINE);
			
			GtkTreeIter iter;
			gtk_list_store_append(store, &iter);
			
			gtk_list_store_set(store, &iter, NAME, name, VALUE, value, -1);
		}
		else if (!strcmp(line, WATCH_MARKER))
		{
			gchar watch[MAXLINE];
			readline(config, watch, MAXLINE);
			wtree_add_watch(watch);
		}
		else
		{
			dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Error reading config file"));
			break;
		}
	}
	if (wrongbreaks)
		dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Some breakpoints can't be set as the files are missed"));
	
	add_empty_row();
//.........这里部分代码省略.........
开发者ID:ittner,项目名称:geany-ctags-plugin,代码行数:101,代码来源:tpage.c


示例13: DEFUN

#endif

DEFUN("readline", Freadline, Sreadline,
      (repv prompt_, repv completer), rep_Subr2)
{
    char *prompt = rep_STRINGP(prompt_) ? ((char *) rep_STR(prompt_)) : "> ";
#ifdef HAVE_LIBREADLINE
    char *input;
    repv ret = Qnil, saved;
    rep_GC_root gc_saved;

    saved = completion_fun;
    completion_fun = completer;
    rep_PUSHGC (gc_saved, saved);
    input = readline (prompt);
    rep_POPGC;
    completion_fun = saved;

    if (input)
    {
	int len = strlen (input);
	if (len > 0)
	    add_history (input);
	ret = rep_make_string (len + 2);
	memcpy (rep_STR(ret), input, len);
	rep_STR(ret)[len] = '\n';
	rep_STR(ret)[len+1] = 0;
	free (input);
    }
    completions = Qnil;
开发者ID:bsmr-linux-window-manager,项目名称:librep,代码行数:30,代码来源:readline.c


示例14: lvm_shell

int lvm_shell(struct cmd_context *cmd, struct cmdline_context *cmdline)
{
	int argc, ret;
	char *input = NULL, *args[MAX_ARGS], **argv;

	rl_readline_name = "lvm";
	rl_attempted_completion_function = (CPPFunction *) _completion;

	_read_history(cmd);

	_cmdline = cmdline;

	_cmdline->interactive = 1;
	while (1) {
		free(input);
		input = readline("lvm> ");

		/* EOF */
		if (!input) {
			printf("\n");
			break;
		}

		/* empty line */
		if (!*input)
			continue;

		add_history(input);

		argv = args;

		if (lvm_split(input, &argc, argv, MAX_ARGS) == MAX_ARGS) {
			log_error("Too many arguments, sorry.");
			continue;
		}

		if (!strcmp(argv[0], "lvm")) {
			argv++;
			argc--;
		}

		if (!argc)
			continue;

		if (!strcmp(argv[0], "quit") || !strcmp(argv[0], "exit")) {
			remove_history(history_length - 1);
			log_error("Exiting.");
			break;
		}

		ret = lvm_run_command(cmd, argc, argv);
		if (ret == ENO_SUCH_CMD)
			log_error("No such command '%s'.  Try 'help'.",
				  argv[0]);

                if ((ret != ECMD_PROCESSED) && !error_message_produced()) {
			log_debug(INTERNAL_ERROR "Failed command did not use log_error");
			log_error("Command failed with status code %d.", ret);
		}
		_write_history();
	}

	free(input);
	return 0;
}
开发者ID:ystk,项目名称:debian-lvm2,代码行数:65,代码来源:lvm.c


示例15: main

int main() {
        printf("Variante %d: %s\n", VARIANTE, VARIANTE_STRING);

#ifdef USE_GUILE
        scm_init_guile();
        /* register "executer" function in scheme */
        scm_c_define_gsubr("executer", 1, 0, 0, executer_wrapper);
#endif

		pidTable = create_pid_list();

		struct sigaction act;
		memset(&act, '\0', sizeof(act));
		act.sa_sigaction = &terminationHandler;
		act.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
		if(sigaction(SIGCHLD, &act, NULL) == -1){
			perror("sigaction");
		}

	while (1) {
		char *line=0;
		char *prompt = "ensishell>";

		/* Readline use some internal memory structure that
		   can not be cleaned at the end of the program. Thus
		   one memory leak per command seems unavoidable yet */
		line = readline(prompt);
		if (line == 0 || ! strncmp(line,"exit", 4)) {
			terminate(line);
		}
		else if(!strncmp(line, "jobs", 4)){
			clean_pid_list(&pidTable);
			print_pid_list(pidTable);
#ifdef USE_GNU_READLINE
		add_history(line);
#endif
			continue;
		}

#ifdef USE_GNU_READLINE
		add_history(line);
#endif


#ifdef USE_GUILE
		/* The line is a scheme command */
		if (line[0] == '(') {
			char catchligne[strlen(line) + 256];
			sprintf(catchligne, "(catch #t (lambda () %s) (lambda (key . parameters) (display \"mauvaise expression/bug en scheme\n\")))", line);
			scm_eval_string(scm_from_locale_string(catchligne));
			free(line);
                        continue;
                }
#endif

		executer(line);
//		struct cmdline *l;
//		int i, j;
//		/* parsecmd free line and set it up to 0 */
//		l = parsecmd( & line);
//
//		/* If input stream closed, normal termination */
//		if (!l) {
//		  
//			terminate(0);
//		}
//		
//
//		
//		if (l->err) {
//			/* Syntax error, read another command */
//			printf("error: %s\n", l->err);
//			continue;
//		}
//
//		if (l->in) printf("in: %s\n", l->in);
//		if (l->out) printf("out: %s\n", l->out);
//		if (l->bg) printf("background (&)\n");
//
//		/* Display each command of the pipe */
//		for (i=0; l->seq[i]!=0; i++) {
//			char **cmd = l->seq[i];
//			printf("seq[%d]: ", i);
//                        for (j=0; cmd[j]!=0; j++) {
//                                printf("'%s' ", cmd[j]);
//                        }
//			printf("\n");
//		}
	}

}
开发者ID:ggramlich26,项目名称:TP2-SEPC,代码行数:91,代码来源:ensishell.c


示例16: MACRO_STR

int Application::run()
{
    std::cout << "***********************************************************" << std::endl <<
                 "* ON  Server  v" << MACRO_STR(DETECTED_ON_VERSION) <<
                            "    (built on " << MACRO_STR(BUILD_DATE) << ")" << std::endl <<
                 "* (c) Copyright 2009 - " << MACRO_STR(BUILD_YEAR) << " IWStudio" << std::endl <<
                 "* Released under GNU General Public License, vesion 2" << std::endl <<
                 "*" << std::endl <<
                 std::endl;


    _INFO(_logModule, "ON Server Starting Up...");
    setApplicationName("ONCoreServer");
    setApplicationVersion(MACRO_STR(DETECTED_ON_VERSION));
    setOrganizationName("IWStudio");
    setOrganizationDomain("iwstudio.hu");

    _INFO(_logModule, "Installing signal handlers");
    connect(new Common::UnixSignalHandler(SIGHUP, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));
    connect(new Common::UnixSignalHandler(SIGINT, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));
    connect(new Common::UnixSignalHandler(SIGQUIT, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));
    connect(new Common::UnixSignalHandler(SIGTERM, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));

    _INFO(_logModule, "Parsing commandline arguments");

    _INFO(_logModule, "Loading config file");

    _INFO(_logModule, "Setting up logger");
    Common::Logger::Instance()->SetLogToStdout(true);
    Common::Logger::Instance()->SetStdoutLogLevel(Common::Logger::Level::Trace);
    Common::Logger::Instance()->SetFileLogLevel(Common::Logger::Level::Trace);
    Common::Logger::Instance()->SetLogFormat(Common::Logger::Format::Csv);
    Common::Logger::Instance()->SetLogFile(QString(getenv("HOME")).append("/ONServerCore.log"));
    Common::Logger::Instance()->FlushStartupBuffer();

    _INFO(_logModule, "Setting up command interface");
    ServerCore::CommandInterface commander;
    connect(&commander, SIGNAL(Quit()), SLOT(quit()));

    _INFO(_logModule, "Starting Readline");
    ServerCore::Readline readline("on> ");
    readline.connect(Common::Logger::Instance().data(), SIGNAL(BeforeLogLine()), SLOT(Disable()),
                     Qt::DirectConnection);
    readline.connect(Common::Logger::Instance().data(), SIGNAL(AfterLogLine()), SLOT(Enable()),
                     Qt::DirectConnection);
    connect(&readline, SIGNAL(EndSignal()), SLOT(quit()));
    commander.connect(&readline, SIGNAL(LineRead(QString)), SLOT(ProcessCommand(QString)));

    _INFO(_logModule, "Start listening");
    ServerCore::Listener listener;
    listener.listen(3214);

    _INFO(_logModule, "ON Server Startup Complete");
    int exitCode = QCoreApplication::exec();
    _INFO(_logModule, "ON Server Shutting Down...");

    Common::Logger::Instance()->disconnect(&readline);
    readline.Disable();

    return exitCode;
}
开发者ID:u-foka,项目名称:on,代码行数:65,代码来源:application.cpp


示例17: build

void build(char *filename) {
  FILE *database = fopen(filename, "r");
  while (!(feof(database))){
    if (first) {
      Node newNode = malloc(sizeof(struct node)); // allocate memory for newNode
      readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
      newNode->key = malloc(strlen(buffer) + 1); // allocate memory for key
      strcpy(newNode->key, buffer); // copy string from buffer to key
    
      readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
      newNode->value = malloc(strlen(buffer) + 1); // allocate memory for value 
      strcpy(newNode->value, buffer); // copy string from buffer to value
    
      newNode->left = NULL;
      newNode->right = NULL;
      root = newNode;
      printf("%s and %s placed in root\n",newNode->key, newNode->value);
      first = 0;
    }
    
    done = 0;
    temp = root;
    Node newNode = malloc(sizeof(struct node)); // allocate memory for newNode
    readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
    if (!count){
      newNode->key = malloc(strlen(buffer) + 1); // allocate memory for key
      strcpy(newNode->key, buffer); // copy string from buffer to key

      readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
      newNode->value = malloc(strlen(buffer) + 1); // allocate memory for value 
      strcpy(newNode->value, buffer); // copy string from buffer to value

      newNode->left = NULL;
      newNode->right = NULL;

      while(!done) {
        if (strcmp(temp->key, newNode->key) < 0) {
          if (temp->right == NULL){
            temp->right = newNode;
            printf("%s and %s was placed to the right\n", newNode->key, newNode->value);
            done = 1;
          }
          else {
            temp = temp->right;
            printf("Continue to the right\n");
          }
        }
 
        else {
          if (temp->left == NULL) 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ readlines函数代码示例发布时间:2022-05-30
下一篇:
C++ readl_relaxed函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap