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

C++ rewind函数代码示例

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

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



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

示例1: wxLogError


//.........这里部分代码省略.........
		strcpy(fname_temp,"/tmp/espeakXXXXXX");
		if((fd_temp = mkstemp(fname_temp)) >= 0)
		{
			close(fd_temp);

			if((f = fopen(fname_temp,"w+")) != NULL)
			{
				f_trans = f;   // write translation rule trace to a temp file
			}
		}
#else
		strcpy(fname_temp,tmpnam(NULL));
		if((f = fopen(fname_temp,"w+")) != NULL)
		{
			f_trans = f;   // write translation rule trace to a temp file
		}
#endif
		t_phonetic->SetDefaultStyle(style_phonetic);
		translate_text = 2;
		break;

	case T_TRANSLATE:
	case MENU_SPEAK_TRANSLATE:
		t_phonetic->SetDefaultStyle(style_phonetic);
		translate_text = 1;
		break;

	case T_TRANSLATE_IPA:
	case MENU_SPEAK_IPA:
		t_phonetic->SetDefaultStyle(style_phonetic_large);

		translate_text = 3;
		break;

	case T_PROCESS:
	case MENU_SPEAK_TEXT:
		if(prosodycanvas == NULL)
		{
			myframe->OnProsody(event);
		}
		prosodycanvas->LayoutData(ph_list,n_ph_list);
		option_phoneme_events = 1;
		option_log_frames = 1;
		MakeWave2(ph_list,n_ph_list);
		option_log_frames = 0;
		break;
	}

	if(translate_text)
	{
		option_phonemes = translate_text;

		option_multibyte = espeakCHARS_AUTO;
		SpeakNextClause(NULL,NULL,2);  // stop speaking file

		strncpy0(buf,t_source->GetValue().mb_str(wxConvUTF8),sizeof(buf));
		phon_out[0] = 0;
		n_ph_list = 0;
		clause_count = 0;

		vp = buf;
		InitText(0);
		while((vp != NULL) && (n_ph_list < N_PH_LIST))
		{
			vp = TranslateClause(translator,NULL,vp,&clause_tone,NULL);
			CalcPitches(translator,clause_tone);
			CalcLengths(translator);

			GetTranslatedPhonemeString(translator->phon_out,sizeof(translator->phon_out));
			if(clause_count++ > 0)
				strcat(phon_out," ||");
			strcat(phon_out,translator->phon_out);
			t_phonetic->SetValue(wxString(translator->phon_out,wxConvUTF8));

			if((n_ph_list + n_phoneme_list) >= N_PH_LIST)
			{
				n_phoneme_list = N_PH_LIST - n_ph_list - n_phoneme_list;
			}

			memcpy(&ph_list[n_ph_list],phoneme_list,sizeof(PHONEME_LIST)*n_phoneme_list);
			n_ph_list += n_phoneme_list;
		}

		t_phonetic->Clear();
		if(option_phonemes == 2)
		{
			option_phonemes=0;
			rewind(f_trans);
			while(fgets(buf,sizeof(buf),f_trans) != NULL)
			{
				t_phonetic->AppendText(wxString(buf,wxConvUTF8));
			}
			t_phonetic->AppendText(_T("---\n"));
			if(f_trans != NULL)
				fclose(f_trans);
			remove(fname_temp);
		}
		t_phonetic->AppendText(wxString(phon_out,wxConvUTF8));
	}
}  // end of TranslDlg::OnCommand
开发者ID:ragb,项目名称:espeak,代码行数:101,代码来源:transldlg.cpp


示例2: read_scoring_file

/*
*	Reads a scoring matrix from the specified file.
*
*	File should be of the following format:
*
*	A	3	-2	-1	-2
*	C	-2	3	-2	-1
*	G	-1	-2	3	-2
*	T	-2	-1	-2	3
*
*	Returns the scoring matrix as a ScoringMatrix struct containting the scoring matrix,
*	a lookup table for indexing into the matrix, and a reverse lookup table for converting
*	the numerical index back to a char.
*/
ScoringMatrix* read_scoring_file(char* scoreFile)
{
	ScoringMatrix* scoring = malloc(sizeof(ScoringMatrix));
	scoring->numChars = 0;
	
	char line[256];
	char* temp;
	int lineLength;
	int numLines = 0;
	int i;
	int j;
	
	FILE* file = fopen(scoreFile, "r");
	
	if (fgets(line, 256, file) != NULL)
	{
		strtok(line, " 	\t\n");
		
		while (strtok(NULL, " 	\t\n") != NULL)
		{
			scoring->numChars++;
		}
	} else
	{
		printf("Unable to read from score file. Exiting.\n");
		exit(1);
	}
	
	rewind(file);
	
	scoring->matrix = malloc(sizeof(int) * (scoring->numChars) * (scoring->numChars));
	scoring->lookupTable = malloc( sizeof(char) * 128 );
	memset(scoring->lookupTable, -1, sizeof(char) * 128);
	
	// setup characters to ignore: space, tab, carriage return, and newline
	scoring->lookupTable[' '] = scoring->lookupTable['\t'] = scoring->lookupTable['\r'] = scoring->lookupTable['\n'] = -19;

	scoring->lookupTableReverse = malloc (sizeof(char) * (scoring->numChars));
	
	for (i = 0; i < scoring->numChars; i++)
	{
		fgets(line, 256, file);

		temp = strtok(line, " \t\n");

		j = 0;
		scoring->lookupTable[temp[0]] = i;
		scoring->lookupTable[temp[0] ^ 32 ] = i;
		
		scoring->lookupTableReverse[i] = temp[0];
		
		while (((temp = strtok(NULL, " \t\n")) != NULL) && j <= scoring->numChars)
		{
			scoring->matrix[ i * (scoring->numChars) + j++] = atoi(temp);
		}
	}

	fclose(file);

	return scoring;
}
开发者ID:watsonmf,项目名称:CSCI-5314,代码行数:75,代码来源:watson_hw4.c


示例3: _variables

Properties::Properties(Data* data, ssize_t* dataIdx)
    : _variables(NULL), _dirPath(NULL), _parent(NULL), _dataIdx(dataIdx), _data(data)
{
    readProperties();
    rewind();
}
开发者ID:114393824,项目名称:Cocos2dxShader,代码行数:6,代码来源:CCProperties.cpp


示例4: dict_foreign_eval_sql

/****************************************************************//**
Evaluate the given foreign key SQL statement.
@return	error code or DB_SUCCESS */
static
ulint
dict_foreign_eval_sql(
/*==================*/
	pars_info_t*	info,	/*!< in: info struct, or NULL */
	const char*	sql,	/*!< in: SQL string to evaluate */
	dict_table_t*	table,	/*!< in: table */
	dict_foreign_t*	foreign,/*!< in: foreign */
	trx_t*		trx)	/*!< in: transaction */
{
	ulint		error;
	FILE*		ef	= dict_foreign_err_file;

	error = que_eval_sql(info, sql, FALSE, trx);

	if (error == DB_DUPLICATE_KEY) {
		mutex_enter(&dict_foreign_err_mutex);
		rewind(ef);
		ut_print_timestamp(ef);
		fputs(" Error in foreign key constraint creation for table ",
		      ef);
		ut_print_name(ef, trx, TRUE, table->name);
		fputs(".\nA foreign key constraint of name ", ef);
		ut_print_name(ef, trx, TRUE, foreign->id);
		fputs("\nalready exists."
		      " (Note that internally InnoDB adds 'databasename'\n"
		      "in front of the user-defined constraint name.)\n"
		      "Note that InnoDB's FOREIGN KEY system tables store\n"
		      "constraint names as case-insensitive, with the\n"
		      "MySQL standard latin1_swedish_ci collation. If you\n"
		      "create tables or databases whose names differ only in\n"
		      "the character case, then collisions in constraint\n"
		      "names can occur. Workaround: name your constraints\n"
		      "explicitly with unique names.\n",
		      ef);

		mutex_exit(&dict_foreign_err_mutex);

		return(error);
	}

	if (error != DB_SUCCESS) {
		fprintf(stderr,
			"InnoDB: Foreign key constraint creation failed:\n"
			"InnoDB: internal error number %lu\n", (ulong) error);

		mutex_enter(&dict_foreign_err_mutex);
		ut_print_timestamp(ef);
		fputs(" Internal error in foreign key constraint creation"
		      " for table ", ef);
		ut_print_name(ef, trx, TRUE, table->name);
		fputs(".\n"
		      "See the MySQL .err log in the datadir"
		      " for more information.\n", ef);
		mutex_exit(&dict_foreign_err_mutex);

		return(error);
	}

	return(DB_SUCCESS);
}
开发者ID:iwonasado,项目名称:android_real_web_server,代码行数:64,代码来源:dict0crea.c


示例5: free

int config_parser_t::read_config(char ***cv, FILE *f)
{
	*cv = (char **)calloc(MAX_CONFIG_LINES, sizeof(char *));
	if(!*cv)
		return -1;

	if(!f)
	{
		free((*cv));
		(*cv) = NULL;
		return -2;
	}

	fseek(f, 0, SEEK_END);
	int len = ftell(f);
	(*cv)[0] = (char *)malloc(len+1);
	if(!(*cv)[0])
	{
		rewind(f);
		free(*cv);
		*cv = NULL;
		return -3;
	}
	rewind(f);
	if(fread((*cv)[0], len, 1, f) < 0)
	{
		free(*cv[0]);
		free(*cv);
		*cv = NULL;
		return -4;
	}
	(*cv)[0][len] = 0;

	char *v = (*cv)[0];
	scanstate_t state = SS_BLANK;
	int arg = 1;
	int start_arg = 0;
	while(*v)
	{
		switch(state)
		{
		  case SS_BLANK:
			if(*v == '"')
			{
				start_arg = 1;
				state = SS_QUOTE;
			}
			else if(*v == '#')
				state = SS_COMMENT;
			else if(*v > ' ')
			{
				start_arg = 1;
				state = SS_WORD;
			}
			break;
		  case SS_QUOTE:
			if(*v == '"')
			{
				*v = 0;
				state = SS_BLANK;
			}
			break;
		  case SS_WORD:
			if(*v <= ' ')
			{
				*v = 0;
				state = SS_BLANK;
			}
			break;
		  case SS_COMMENT:
			if((*v == 10) || (*v == 13))
				state = SS_BLANK;
			break;
		}
		if(start_arg)
		{
			if(arg < MAX_CONFIG_LINES)
			{
				if(state == SS_QUOTE)
					(*cv)[arg++] = v+1;
				else
					(*cv)[arg++] = v;
			}
			start_arg = 0;
		}
		++v;
	}
	rewind(f);
	return arg;
}
开发者ID:kuwanger,项目名称:kobodl_gcw0,代码行数:90,代码来源:cfgparse.cpp


示例6: if

int CFile::PImpl::open(const char *name, long openflags)
{
	char buf[512];
	const char *openstring;

	if ((openflags & CL_OPEN_READ) && (openflags & CL_OPEN_WRITE)) {
		openstring = "rwb";
	} else if (openflags & CL_OPEN_READ) {
		openstring = "rb";
	} else if (openflags & CL_OPEN_WRITE) {
		openstring = "wb";
	} else {
		DebugPrint("Bad CLopen flags");
		Assert(0);
		return -1;
	}

	cl_type = CLF_TYPE_INVALID;

	if (openflags & CL_OPEN_WRITE) {
#ifdef USE_BZ2LIB
		if ((openflags & CL_WRITE_BZ2)
			&& (cl_bz = BZ2_bzopen(strcat(strcpy(buf, name), ".bz2"), openstring))) {
			cl_type = CLF_TYPE_BZIP2;
		} else
#endif
#ifdef USE_ZLIB
			if ((openflags & CL_WRITE_GZ)
				&& (cl_gz = gzopen(strcat(strcpy(buf, name), ".gz"), openstring))) {
				cl_type = CLF_TYPE_GZIP;
			} else
#endif
				if ((cl_plain = fopen(name, openstring))) {
					cl_type = CLF_TYPE_PLAIN;
				}
	} else {
		if (!(cl_plain = fopen(name, openstring))) { // try plain first
#ifdef USE_ZLIB
			if ((cl_gz = gzopen(strcat(strcpy(buf, name), ".gz"), "rb"))) {
				cl_type = CLF_TYPE_GZIP;
			} else
#endif
#ifdef USE_BZ2LIB
				if ((cl_bz = BZ2_bzopen(strcat(strcpy(buf, name), ".bz2"), "rb"))) {
					cl_type = CLF_TYPE_BZIP2;
				} else
#endif
				{ }

		} else {
			cl_type = CLF_TYPE_PLAIN;
			// Hmm, plain worked, but nevertheless the file may be compressed!
			if (fread(buf, 2, 1, cl_plain) == 1) {
#ifdef USE_BZ2LIB
				if (buf[0] == 'B' && buf[1] == 'Z') {
					fclose(cl_plain);
					if ((cl_bz = BZ2_bzopen(name, "rb"))) {
						cl_type = CLF_TYPE_BZIP2;
					} else {
						if (!(cl_plain = fopen(name, "rb"))) {
							cl_type = CLF_TYPE_INVALID;
						}
					}
				}
#endif // USE_BZ2LIB
#ifdef USE_ZLIB
				if (buf[0] == 0x1f) { // don't check for buf[1] == 0x8b, so that old compress also works!
					fclose(cl_plain);
					if ((cl_gz = gzopen(name, "rb"))) {
						cl_type = CLF_TYPE_GZIP;
					} else {
						if (!(cl_plain = fopen(name, "rb"))) {
							cl_type = CLF_TYPE_INVALID;
						}
					}
				}
#endif // USE_ZLIB
			}
			if (cl_type == CLF_TYPE_PLAIN) { // ok, it is not compressed
				rewind(cl_plain);
			}
		}
	}

	if (cl_type == CLF_TYPE_INVALID) {
		//fprintf(stderr, "%s in ", buf);
		return -1;
	}
	return 0;
}
开发者ID:realhidden,项目名称:stratagus,代码行数:90,代码来源:iolib.cpp


示例7: SetValueToEtcFile

/* Function: SetValueToEtcFile(const char* pEtcFile, const char* pSection,
 *                               const char* pKey, char* pValue);
 * Parameter:
 *     pEtcFile: etc file path name.
 *     pSection: Section name.
 *     pKey:     Key name.
 *     pValue:   Value.
 * Return:
 *     int                      meaning
 *     ETC_FILENOTFOUND         The etc file not found.
 *     ETC_TMPFILEFAILED        Create tmp file failure.
 *     ETC_OK                   OK.
 */
int GUIAPI SetValueToEtcFile (const char* pEtcFile, const char* pSection,
                               const char* pKey, char* pValue)
{
    FILE* etc_fp;
    FILE* tmp_fp;
    int rc;
    char tempSection [ETC_MAXLINE + 2];

#ifndef HAVE_TMPFILE
    char tmp_nam [256];

    sprintf (tmp_nam, "/tmp/mg-etc-tmp-%x", time(NULL));
    if ((tmp_fp = fopen (tmp_nam, "w+")) == NULL)
        return ETC_TMPFILEFAILED;
#else
    if ((tmp_fp = tmpfile ()) == NULL)
        return ETC_TMPFILEFAILED;
#endif

    if (!(etc_fp = fopen (pEtcFile, "r+"))) {
        fclose (tmp_fp);
#ifndef HAVE_TMPFILE
        unlink (tmp_nam);
#endif
        if (!(etc_fp = fopen (pEtcFile, "w"))) {
            return ETC_FILEIOFAILED;
        }
        fprintf (etc_fp, "[%s]\n", pSection);
        fprintf (etc_fp, "%s=%s\n", pKey, pValue);
        fclose (etc_fp);
        return ETC_OK;
    }

    switch (etc_CopyAndLocate (etc_fp, tmp_fp, pSection, pKey, tempSection)) {
    case ETC_SECTIONNOTFOUND:
        fprintf (tmp_fp, "\n[%s]\n", pSection);
        fprintf (tmp_fp, "%s=%s\n", pKey, pValue);
        break;
    
    case ETC_KEYNOTFOUND:
        fprintf (tmp_fp, "%s=%s\n\n", pKey, pValue);
        fprintf (tmp_fp, "%s\n", tempSection);
    break;

    default:
        fprintf (tmp_fp, "%s=%s\n", pKey, pValue);
        break;
    }

    if ((rc = etc_FileCopy (etc_fp, tmp_fp)) != ETC_OK)
        goto error;
    
    // replace etc content with tmp file content
    // truncate etc content first
    fclose (etc_fp);
    if (!(etc_fp = fopen (pEtcFile, "w"))) {
        fclose (tmp_fp);
#ifndef HAVE_TMPFILE
        unlink (tmp_nam);
#endif
        return ETC_FILEIOFAILED;
    }
    
    rewind (tmp_fp);
    rc = etc_FileCopy (tmp_fp, etc_fp);

error:
    fclose (etc_fp);
    fclose (tmp_fp);
#ifndef HAVE_TMPFILE
    unlink (tmp_nam);
#endif
    return rc;
}
开发者ID:channinglan,项目名称:MINIGUI_1.3.3,代码行数:87,代码来源:misc.c


示例8: booksave

int booksave(void)
{
    struct book library[MAXBKS]; /* array of structures     */
    int count = 0;
    int index, filecount;
    FILE * pbooks;
    int size = sizeof (struct book);

    if ((pbooks = fopen("book.txt", "a+b")) == NULL)
    {
        fputs("Can't open book.txt file\n",stderr);
        exit(1);
    }
    
    rewind(pbooks);            /* go to start of file     */
    while (count < MAXBKS &&  fread(&library[count], size,
                1, pbooks) == 1)
    {
        if (count == 0)
            puts("Current contents of book.dat:");
        printf("%s by %s: $%.2f\n",library[count].title,
            library[count].author, library[count].value);
        count++;
    }
    filecount = count;
    if (count == MAXBKS)
    {
        fputs("The book.dat file is full.", stderr);
        exit(2);
    }
    
    puts("Please add new book titles.");
    puts("Press [enter] at the start of a line to stop.");
    while (count < MAXBKS && gets(library[count].title) != NULL
                          && library[count].title[0] != '\0')
    {
        puts("Now enter the author.");
        gets(library[count].author);
        puts("Now enter the value.");
		scanf("%f", &library[count++].value);
        while (getchar() != '\n')
            continue;                /* clear input line  */
         if (count < MAXBKS)
             puts("Enter the next title.");
    }
    
    if (count > 0)
    { 	
        puts("Here is the list of your books:");
        for (index = 0; index < count; index++)
            printf("%s by %s: $%.2f\n",library[index].title,
                   library[index].author, library[index].value);
        fwrite(&library[filecount], size, count - filecount,
                pbooks);
    }
    else
    	puts("No books? Too bad.\n");
    
    puts("Bye.\n");
    fclose(pbooks);
    
    return 0;
}
开发者ID:tuling56,项目名称:CPP,代码行数:63,代码来源:booksave.c


示例9: init_ram_segments

static void
init_ram_segments(void)
{
	int i, errflag;
        FILE *iomem; 
	char buf[BUFSIZE], *p1, *p2;
	physaddr_t start, end;

	if ((iomem = fopen("/proc/iomem", "r")) == NULL)
		goto fail_iomem;

	while (fgets(buf, BUFSIZE, iomem)) {
		if (strstr(buf, "System RAM")) {
			console(buf);
			nr_segments++;
		}
	}
	if (!nr_segments)
		goto fail_iomem;

	ram_segments = (struct ram_segments *)
		GETBUF(sizeof(struct ram_segments) * nr_segments);

	rewind(iomem);
	i = 0;
	while (fgets(buf, BUFSIZE, iomem)) {
		if (strstr(buf, "System RAM")) {
			if (!(p1 = strstr(buf, ":")))
				goto fail_iomem;
			*p1 = NULLCHAR;
			clean_line(buf);
			if (strstr(buf, " "))
				goto fail_iomem;
			p1 = buf;
			if (!(p2 = strstr(buf, "-")))
				goto fail_iomem;
			*p2 = NULLCHAR;
			p2++;
			errflag = 0;
			start = htoll(p1, RETURN_ON_ERROR|QUIET, &errflag);
			end = htoll(p2, RETURN_ON_ERROR|QUIET, &errflag);
			if (errflag)
				goto fail_iomem;
			ram_segments[i].start = PHYSPAGEBASE(start);
			if (PAGEOFFSET(start))
				ram_segments[i].start += PAGESIZE();
			ram_segments[i].end = PHYSPAGEBASE(end);
			if (PAGEOFFSET(end) == (PAGESIZE()-1))
				ram_segments[i].end += PAGESIZE();
			console("ram_segments[%d]: %016llx %016llx [%s-%s]\n", i,
				(ulonglong)ram_segments[i].start, 
				(ulonglong)ram_segments[i].end, p1, p2);
			i++;
		}
	}

	fclose(iomem);
	return;

fail_iomem:
	fclose(iomem);
	nr_segments = 0;
	if (ram_segments)
		FREEBUF(ram_segments);

	return; 
}
开发者ID:crash-utility,项目名称:crash,代码行数:67,代码来源:snap.c


示例10: set_value_thread

void* set_value_thread(void *context)
{
	sensor_context *sensor = NULL;
	message msg;
	int return_value;
	char *tokens[10];
	char line[LINE_MAX];
	int count = 0;
	int start, end, value;

	sensor = (sensor_context*)context;

	msg.type = CURRENT_VALUE;
	while(sensor->run)
	{
		if(!(start <= sensor->clock && sensor->clock < end))
		{
			/* Figure out the value from file */
			if(fgets(line, LINE_MAX, sensor->sensor_value_file_pointer) == NULL)
			{
				LOG_DEBUG(("DEBUG: Seeking to beginning of file"));
				rewind(sensor->sensor_value_file_pointer);
				sensor->clock = 0;
				continue;
			}

			str_tokenize(line, ";\n\r", tokens, &count);
			if(count != 3)
			{
				LOG_ERROR(("ERROR: Wrong sensor temperature value file\n"));
				break;
			}

			start = atoi(tokens[0]);
			end = atoi(tokens[1]);
			if(strcmp (tokens[2], "true") == 0)
			{
				value = 1; 
			}
			else
			{
				value = 0;
			}
			sensor->value = value;
		}

		msg.u.value = sensor->value;
		msg.timestamp = time(NULL);

		pthread_mutex_lock(&sensor->mutex_lock);

		sensor->logical_clock[2]++;
		LOG_SCREEN(("INFO: Event Sent, "));
		LOG_INFO(("INFO: Event Sent, "));
		print_logical_clock_to_screen(sensor->logical_clock);
		print_logical_clock(sensor->logical_clock);
		LOG_INFO(("timestamp: %lu, Motion: %s\n", msg.timestamp, tokens[2]));
		LOG_SCREEN(("timestamp: %lu, Motion: %s\n", msg.timestamp, tokens[2]));
		return_value = write_message(sensor->socket_fd, sensor->logical_clock, &msg);
		if(E_SUCCESS != return_value)
		{
			LOG_ERROR(("ERROR: Error in sending sensor temperature value to gateway\n"));
		}

		for(int index=0; index<sensor->send_peer_count; index++)
		{
			return_value = write_message(sensor->send_peer[index]->comm_socket_fd,
					sensor->logical_clock,
					&msg);
			if(E_SUCCESS != return_value)
			{
				LOG_ERROR(("ERROR: Error in sending sensor temperature value to peer\n"));
			}
		}
		pthread_mutex_unlock(&sensor->mutex_lock);

		sleep(sensor->interval);
		sensor->clock += sensor->interval;
	}

	LOG_DEBUG(("Exiting SetValueThread...\n"));
	return (NULL);
}
开发者ID:abhijeet-wadkar,项目名称:IoT-security-system-simulation,代码行数:83,代码来源:key_chain_sensor.c


示例11: KpeGetKALHelp

/****************************************************************************
 * Creator: T. M. Farrington
 * Purpose: To search a binary file that contains command syntaxes.
 *
 * Inputs:  One binary file, the name of which is defined in the include file.
 *          Character pointer to the function name to be looked up.
 *          Character pointer to a buffer where the full command syntax will
 *             be placed if it is found.
 *          Maximum string size that the buffer can receive.
 *
 * Outputs: Return TRUE if search was successful, FALSE if not.
 *          If TRUE, places full command syntax in the buffer.
 *
 ****************************************************************************/
int W_EXPORT KpeGetKALHelp(LPSTR fnameptr, LPSTR buffer, int maxsiz)
{
    FILE *finptr;
    int iFile;
    OFSTRUCT of;
    char pFullPath[FILENAME_MAX];
    unsigned short csfname = lstrlen(fnameptr) + 1;
    unsigned short ssfname, ssrecord;
    unsigned short found = FALSE;

    /* First look for the file in KAPPA's system directory. *
     * If not there, then use the PATH.                     */
    KppGetSystemDirectory(pFullPath, FILENAME_MAX);
    strncat(pFullPath, binary_file, FILENAME_MAX - strlen(pFullPath) - 1);
    if ((iFile = OpenFile(pFullPath, &of, OF_READ)) == -1)
        iFile = OpenFile(binary_file, &of, OF_READ);

    if ((iFile == -1) || ((finptr = fdopen(iFile, "rb")) == NULL))
    {
        RegisterKappaMessage(IDE_FCANTOPEN,
                             KppAddAtom(binary_file), NULLID, NULLID);
        KppIncrementPopupCountCB(EDITW);
        PostKappaMessage();
        KppDecrementPopupCountCB(EDITW);
        return FALSE;
    }

    rewind(finptr);

    /* While not found, get the two string length values (2 bytes each)
     * at the begining of the record. 
     */
    while (!found)
    {
        fread(&ssfname, 2, 1, finptr);
        if (feof(finptr))
            break;

        fread(&ssrecord, 2, 1, finptr);
        if (feof(finptr))
            break;

        /* If the size of the parameter function name ==
            * size of the scanned function name,
                */
        if (csfname == ssfname)
        {
            char data[MAX_RECORD_LENGTH];

            /* then read the function name and if the strings match, */
            if ((fread(data, ssfname, 1, finptr) != NULL) &&
                (!lstrcmp(fnameptr, data)))
            {
                /* get the rest of the record and concatenate both strings
                    into the output file,
                        RBP: Do not concatenate */
                /* kstrcpy (buffer, data, maxsiz); */
                if (fread(data, ssrecord - ssfname - 4, 1, finptr) != NULL)
                    _fstrncpy(buffer, data, maxsiz);

                /* Stop the search. */
                found = TRUE;
            }
            else
                /* otherwise advance the file pointer to the next record.*/
                fseek(finptr, (long) ssrecord - 4 - ssfname, SEEK_CUR);
        }
        else                        /* otherwise advance the file pointer to the next record. */
            fseek(finptr, (long) ssrecord - 4, SEEK_CUR);
    }

    fclose(finptr);

    if (!found && (KppGetKalFunctionSyntaxCB(KppCheckAtom(fnameptr),
                                             buffer, maxsiz) != -1 ||
                   KppGetDLLFunctionSyntax(fnameptr, buffer, maxsiz) != -1))
        found = TRUE;

    return found;
}
开发者ID:thearttrooper,项目名称:KappaPC,代码行数:94,代码来源:EDITHLP.C


示例12: initialRun

/*Initial run, read in given file and save sorted blocks to temporary files*/
BOOLEAN initialRun(char * filePath, int bufferMemoryCount, Schema * schema, FileList * fileL, int * totalRecordCount){
	FILE * initialFP;
	char line[LINE_LENGTH];
	char * tokenPtr;
	int i;

/*Open path file*/
	if((initialFP = fopen(filePath,"r")) == NULL){
		fprintf(stderr, "Error: Failed to open file %s\n",filePath);
		return FALSE;
	}

/*Determine and set type of file data*/
/*Get first line of file and count number of ','*/
	fgets(line, LINE_LENGTH, initialFP);
/*rewind to start of file for future use*/
	rewind(initialFP);
/*Determine first occurrence of ',' in line*/
	tokenPtr = strchr(line,',');
/*Determine if there is a second occurrence of ',' in line*/
	tokenPtr = strchr(tokenPtr+1,',');
/*if NULL then file contains guild records*/
/*(since there is only 1 ',' for every guild file line)*/
	if(tokenPtr == NULL)
		*schema = GUILD;
/*else then file contains character records*/
	else
		*schema = CHARACTER;

/*While there is still more of the file to read*/
	while (line[0] != '\0'){
		FILE * tempFP;
		int recordCount = bufferMemoryCount;
		Record * records = calloc(bufferMemoryCount, sizeof(Record));
		if (!records){
			fprintf(stderr, "Error: Failed to allocate memory for records\n");
			return FALSE;
		}

		for(i = 0; i < bufferMemoryCount; i++){
			char * tempString = NULL;
/*If reached end of file*/
			if(fgets(line, LINE_LENGTH, initialFP) == NULL){
/*set record size to index reached*/
				recordCount = i;
				line[0] = '\0';
				break;
			}

			if(*schema == CHARACTER){
				strcpy(records[i].field.character.cname,strtok(line,","));

				tempString = strtok(NULL,",");
				records[i].field.character.team = (unsigned short int) strtoul(tempString, NULL, 0);

				tempString = strtok(NULL,",");
				records[i].field.character.level = (unsigned short int) strtoul(tempString, NULL, 0);

				tempString = strtok(NULL,",");
				records[i].field.character.cid = (unsigned int) strtoul(tempString, NULL, 0);

				tempString = strtok(NULL,",");
				records[i].GuildID = (unsigned int) strtoul(tempString, NULL, 0);
			}
			else{ /*If GUILD schema*/
				int lineLen = strlen(line);
				/*Remove new line from end of string*/
				if (lineLen > 0 && line[lineLen-1] == '\n')
					line[lineLen-1] = '\0';

				tempString = strtok(line,",");
				records[i].GuildID = (unsigned int) strtoul(tempString, NULL, 0);

				strcpy(records[i].field.g_name,strtok(NULL,","));
			}
			*totalRecordCount = *totalRecordCount +1;
		}

		/*Sort the blocks*/
		quickSort(records, 0, recordCount-1);
		/*insertionSort(records, recordCount);*/
	/*Write out buffers run of B blocks to temp files*/
	/*create temporary file*/
		if((tempFP = tmpfile()) == NULL){
			fprintf(stderr, "Error: Failed to create temporary file\n");
			return FALSE;
		}

/*Write array of records to binary file*/
		fwrite(records, sizeof(Record), recordCount, tempFP);
/*no need to loop through records array*/
/*for (i = 0; i < recordCount; i++){
fwrite(&records[i], sizeof(Record), 1, tempFP);
}*/

		/*Rewind temp file pointer for later merging*/
		rewind(tempFP);
		/*add file pointer to file list*/
		addFile(fileL, tempFP);
//.........这里部分代码省略.........
开发者ID:caspez,项目名称:External-Merge-Sort,代码行数:101,代码来源:sort.c


示例13: mergeRuns


//.........这里部分代码省略.........
				addRecord(&bufferNodes[outputBuffIndex],
					minIndex.buff->pageRecords[minIndex.pgIndex], pagesize, bufferNodes[outputBuffIndex].recordCount);
/*remove the same record from original buffer*/
				removeRecord(minIndex.buff, minIndex.pgIndex);
/*if output buffer is full, write page to file*/
				if(bufferNodes[outputBuffIndex].recordCount == pagesize){
/*write page to file*/
					int written;
					written = fwrite(bufferNodes[outputBuffIndex].pageRecords, sizeof(Record),
						pagesize, outputFile);
					if(written !=pagesize){
						fprintf(stderr, "Error: Failed to write to output file, wrote %i records\n",written);
						return FALSE;
					}

					/*clear page in output buffer*/
					clearPage(&bufferNodes[outputBuffIndex], pagesize);
				}

/*if original buffer is empty, read in another page*/
				if(minIndex.buff->recordCount == 0){
					int recordPageIndex;
/*fill buffer with records from file*/
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						Record record;
						if(minIndex.buff->fileNode->fp != NULL){
							if(fread(&record, sizeof(Record), 1, minIndex.buff->fileNode->fp) == 1){
		/*add record to page (records array)*/
								if(addRecord(minIndex.buff, record, pagesize, recordPageIndex) == FALSE)
									return FALSE;
		/*add record index to heap*/
								if(addToHeap(&rHeap, minIndex.buff, recordPageIndex) == FALSE)
									return FALSE;
							}
		/*else reached file end*/
							else{
								/*temp file will be automatically deleted by the system*/
								fclose(minIndex.buff->fileNode->fp);
								minIndex.buff->fileNode->fp = NULL;
								/*removeFile(currentFiles, minIndex.buff->fileNode);*/
								break;
							}
						}
					}
				}
/*if buffer is still empty, then 0 records were read in,
therefore file is empty and the buffer is now free*/
				if(minIndex.buff->recordCount == 0)
					/*decrement buffers in use counter*/
					buffersInUse--;
			}

/*All files for run have been fully read*/
/*Write out records still in output buffer*/
			if(bufferNodes[outputBuffIndex].recordCount > 0){
/*Output buffer page was not full*/
				int i = 0;
				for(i = 0; i < pagesize; i++){
					if(bufferNodes[outputBuffIndex].pageRecords[i].GuildID != 0){
						fwrite(&bufferNodes[outputBuffIndex].pageRecords[i],
							sizeof(Record), 1, outputFile);
						removeRecord(&bufferNodes[outputBuffIndex], i);
					}
				}
			}
			/*Rewind outfile for future merge*/
			rewind(outputFile);
			runCount++;
		}
		/*set runFileListas new current file list*/
		freeFileNode(&currentFiles);
		currentFiles = runFileList;
		*passes = *passes+1;
		*runs = *runs + runCount;
		printf("Pass %i resulted in %i runs\n",*passes,runCount);
	}


/*FileList will contain link to only 1 temporary binary file*/
	if(currentFiles.fileCount != 1){
		fprintf(stderr, "Error: Number of files:%i is invalid\n",currentFiles.fileCount);
		return FALSE;
	}
	*sorted = currentFiles.fileHeadNode->fp;

	/*free allocated memory*/

	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		freeBuffer(&bufferNodes[bufferIndex]);
	}
	free(bufferNodes);

	freeHeap(&rHeap);

	freeFileNode(&currentFiles);

	/*free(currentFiles);*/

	return TRUE;
}
开发者ID:caspez,项目名称:External-Merge-Sort,代码行数:101,代码来源:sort.c


示例14: main

int main(int argc, char **argv)
{
	char dumpTableFile[] = "table.txt" ;	  
	char inputFile[] = "../test/data/test_input" ;
	char patternFile[] = "../test/pattern/space_pattern" ;
	PFAC_handle_t handle ;
	PFAC_status_t PFAC_status ;
	int input_size ;    
	char *h_inputString = NULL ;
	int  *h_matched_result = NULL ;
	
	char *h_inputString_buf = NULL;

	// step 1: create PFAC handle 
	PFAC_status = PFAC_create( &handle ) ;
	assert( PFAC_STATUS_SUCCESS == PFAC_status );

	// step 2: read patterns and dump transition table
	PFAC_status = PFAC_readPatternFromFile( handle, patternFile) ;
	if ( PFAC_STATUS_SUCCESS != PFAC_status ){
		printf("Error: fails to read pattern from file, %s\n", PFAC_getErrorString(PFAC_status) );
		exit(1) ;
	}

	// dump transition table 
	FILE *table_fp = fopen( dumpTableFile, "w") ;
	assert( NULL != table_fp ) ;
	PFAC_status = PFAC_dumpTransitionTable( handle, table_fp );
	fclose( table_fp ) ;
	if ( PFAC_STATUS_SUCCESS != PFAC_status ){
		printf("Error: fails to dump transition table, %s\n", PFAC_getErrorString(PFAC_status) );
		exit(1) ;	
	}

	if (argc <= 1){
		printf("no input arguments, using default value\n"); 	

		//step 3: prepare input stream
		FILE* fpin = fopen( inputFile, "rb");
		assert ( NULL != fpin ) ;

		// obtain file size
		fseek (fpin , 0 , SEEK_END);
		input_size = ftell (fpin)-1;
		rewind (fpin);  

		printf("input_size is %d\n", input_size);
		// allocate memory to contain the whole file
		h_inputString = (char *) malloc (sizeof(char)*input_size);
		assert( NULL != h_inputString );

		h_matched_result = (int *) malloc (sizeof(int)*input_size);
		assert( NULL != h_matched_result );
		memset( h_matched_result, 0, sizeof(int)*input_size ) ;

		// copy the file into the buffer
		input_size = fread (h_inputString, 1, input_size, fpin);
		fclose(fpin);    
	}
	else{
		// step 3: prepare input string
		processCommandOption(argc, argv, &h_inputString);		

		input_size = strlen(h_inputString);	

		h_matched_result = (int *) malloc (sizeof(int)*input_size);	
				
		memset (h_matched_result, 0, sizeof(int)*input_size);	
	}

	// step 4: run PFAC on GPU           
	PFAC_status = PFAC_matchFromHost( handle, h_inputString, input_size, h_matched_result ) ;
	if ( PFAC_STATUS_SUCCESS != PFAC_status ){
		printf("Error: fails to PFAC_matchFromHost, %s\n", PFAC_getErrorString(PFAC_status) );
		exit(1) ;	
	}     

	// step 5: output matched result
	// parse in serial, GPU version should be considered
	std::vector<int> positionQ;
	int keylen, i;
	for (int i = 0; i < input_size; i++) {
		if (h_matched_result[i] != 0)  {
			positionQ.push_back(i+1);
		}
		else if (i == 0) {
			positionQ.push_back(i);
		}
	}
	
	for (i = 0; i < positionQ.size(); i++){
		keylen = positionQ[i+1]-positionQ[i];

		// if keylen < 0, this means this is the last element
		// in h_inputString array,
		if (keylen == 1){
			continue;
		} else if (keylen < 0){
			keylen = input_size - positionQ[i];

//.........这里部分代码省略.........
开发者ID:sufengniu,项目名称:RXP,代码行数:101,代码来源:simple_opt.cpp


示例15: rewind

void CastleGame::seeker(char *sstring)
{
	rewind(fptr);
	while(fseeker(sstring) != FSUCCESS){}
}
开发者ID:beemfx,项目名称:Castle,代码行数:5,代码来源:WCastle.cpp


示例16: while

int LuaObfuscator::addFalseComment() {
	int size = 0;
	// The list of false comment...
	// or
	// generate the false comment...

	char szFileNameNew[MAX_PATH];

	// read global functions
	StringListConstIter iter = m_luaFiles.begin();
	while (iter != m_luaFiles.end()) {
		FILE *file = fopen(iter->c_str(), "rt");
		if (!file) {
			print("File not found: %s", iter->c_str());
			++iter;
			continue;
		}
		fseek(file, 0, SEEK_END);
		long fileSize = ftell(file);
		rewind(file);
		char *pDataInSource = new char[fileSize + 20];
		char *pDataIn = pDataInSource + 10;
		memset(pDataInSource, 0, 10);
		size_t realSize = fread(pDataIn, sizeof(char), fileSize, file);
		memset(pDataIn + realSize, 0, 10);
		fclose(file);

		generateNewFileName(szFileNameNew, iter->c_str());

		file = fopen(szFileNameNew, "wt");
		char *p = pDataIn;
		while (*p) {
			if (isStringStart(p)) {
				char *pStart = p;
				size_t stringSize = skipStringAndMove(&p, NULL);
				if (stringSize) {
					fwrite(pStart, 1, stringSize, file);
					//obfuscateSize += len + 1;
					continue;
				}
				else {
					print("Start of line are found, but end of line not found\n");
					break;
				}
			}
			if (strchr(";,\n+*/%^", *p)) {
				char szAddComment[100];
				size_t len = generateFalseComment(szAddComment);
				fwrite(szAddComment, 1, len, file);
				fputc(*p, file);
				++p;
			//obfuscateSize += len + 1;
				continue;
			}
			fputc(*p, file);
			//++obfuscateSize;
			++p;
		}
		long obfuscateSize = ftell(file);
		fclose(file);
		delete[] pDataInSource;

		print("%8d %s\n", obfuscateSize - fileSize, szFileNameNew);
		size += obfuscateSize - fileSize;
		++iter;
	}

	return size;
}
开发者ID:gracerpro,项目名称:luaob,代码行数:69,代码来源:obfuscator.cpp


示例17: rsa_gen_keys

// Calling this function will generate a public and private key and store them in the pointers
// it is given. 
void rsa_gen_keys(struct public_key_class *pub, struct private_key_class *priv, char *PRIME_SOURCE_FILE)
{
  FILE *primes_list;
  if(!(primes_list = fopen(PRIME_SOURCE_FILE, "r"))){
    fprintf(stderr, "Problem reading %s\n", PRIME_SOURCE_FILE);
    exit(1);
  }

  // count number of primes in the list
  long long prime_count = 0;
  do{
    int bytes_read = fread(buffer,1,sizeof(buffer)-1, primes_list);
    buffer[bytes_read] = '\0';
    for (i=0 ; buffer[i]; i++){
      if (buffer[i] == '\n'){
	prime_count++;
      }
    }
  }
  while(feof(primes_list) == 0);
  
  
  // choose random primes from the list, store them as p,q

  long long p = 0;
  long long q = 0;

  long long e = powl(2, 8) + 1;
  long long d = 0;
  char prime_buffer[MAX_DIGITS];
  long long max = 0;
  long long phi_max = 0;
  
  srand(time(NULL));
  
  do{
    // a and b are the positions of p and q in the list
    int a =  (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
    int b =  (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
    
    // here we find the prime at position a, store it as p
    rewind(primes_list);
    for(i=0; i < a + 1; i++){
    //  for(j=0; j < MAX_DIGITS; j++){
    //	prime_buffer[j] = 0;
    //  }
      fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
    }
    p = atol(prime_buffer); 
    
    // here we find the prime at position b, store it as q
    rewind(primes_list);
    for(i=0; i < b + 1; i++){
      for(j=0; j < MAX_DIGITS; j++){
	prime_buffer[j] = 0;
      }
      fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
    }
    q = atol(prime_buffer); 

    max = p*q;
    phi_max = (p-1)*(q-1);
  }
  while(!(p && q) || (p == q) || (gcd(phi_max, e) != 1));
 
  // Next, we need to choose a,b, so that a*max+b*e = gcd(max,e). We actually only need b
  // here, and in keeping with the usual notation of RSA we'll call it d. We'd also like 
  // to make sure we get a representation of d as positive, hence the while loop.
  d = ExtEuclid(phi_max,e);
  while(d < 0){
    d = d+phi_max;
  }

  printf("primes are %lld and %lld\n",(long long)p, (long long )q);
  // We now store the public / private keys in the appropriate structs
  pub->modulus = max;
  pub->exponent = e;

  priv->modulus = max;
  priv->exponent = d;
}
开发者ID:sankarmanoj,项目名称:HomeAutomation,代码行数:83,代码来源:rsa.c


示例18: main

int main(int argc, char **argv)
{
	FILE *file;
	int i, j;
	unsigned file_size;
	pthread_mutex_init(&mutex, NULL);
	j = 0;
	hash_sum = 1;
	unsigned short cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
	struct sysinfo si;
	sysinfo(&si);
	printf("Free RAM\t=\t%lu B or %f MB\n", si.freeram,
			((double)si.freeram * (double)si.mem_unit) / 1048576.0);
	printf("Core(s) avaible =\t%u\n", cpu_count);
	file = fopen(argv[1], "rb");
	if (file < 0) {
		perror("Cant open file");
		print("Usage: chsum /full/path/to/file [force_num_threads]");
		exit(EXIT_FAILURE);
	}
	fseek(file, 0, SEEK_END);
	file_size = ftell(file);
	rewind(file);
	printf("Size of file\t=\t%u\n", file_size);
	unsigned num_size = ceil(file_size / (0.3 * si.freeram));
	unsigned free_size = file_size;
	struct timespec t_before, t_after;
	clock_gettime(CLOCK_BOOTTIME, &t_before);
	printf("Start time\t=\t%lu sec and %lu nsec\n",
			t_before.tv_sec, t_before.tv_nsec);
	while (j < num_size) {
		if (free_size < 0.3 * si.freeram) {
			n = ceil(free_size / sizeof(short));
			mas = (short *)malloc(n * sizeof(short));
			sum_exp = (float *)malloc(n * sizeof(float));
		} else {
			n = ceil(0.3 * si.freeram / sizeof(short));
			mas = (short *)malloc(n * sizeof(short));
			sum_exp = (float *)malloc(n * sizeof(float));
			free_size = free_size - 0.3 * si.freeram;
		}
		fread(mas, n * sizeof(short), 1, file);
		fseek(file, n * sizeof(short), SEEK_CUR);
		if (argc == 3)
			cpu_count = atoi(argv[2]);
		printf("Threads number\t=\t%d\n", cpu_count);
		pthread_t id[cpu_count];
		for (i = 0; i < cpu_count; i++) {
			if (pthread_create(&id[i], NULL, work, NULL)) {
					printf("Thread creating error\n");
					exit(EXIT_FAILURE);
			}
		}
		for (i = 0; i < cpu_count; i++)
			pthread_join(id[i], NULL);
		j++;
	}
	clock_gettime(CLOCK_BOOTTIME, &t_after);
	printf("End time\t=\t%lu sec and %lu nsec\n",
			t_after.tv_sec, t_after.tv_nsec);
	long long start, end, diff, res_in_microsec;
	start = t_before.tv_sec*NANOS + t_before.tv_nsec;
	end = t_after.tv_sec*NANOS + t_after.tv_nsec;
	diff = end - start;
	res_in_microsec = diff / 1000 + (diff % 1000 >= 500);
	printf("Elapse time\t=\t%lld microsec\n", res_in_microsec);
	printf("Hash\t\t=\t%.20f\n", hash_sum);
	fclose(file);
	return 0;
}
开发者ID:Cold-D,项目名称:chksum,代码行数:70,代码来源:src.c


示例19: replaceGlobalFunctions

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ rewinddir函数代码示例发布时间:2022-05-30
下一篇:
C++ revert函数代码示例发布时间: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