本文整理汇总了C++中rewind函数的典型用法代码示例。如果您正苦于以下问题:C++ rewind函数的具体用法?C++ rewind怎么用?C++ rewind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rewind函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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;
}
示例3: _variables
Properties::Properties(Data* data, ssize_t* dataIdx)
: _variables(NULL), _dirPath(NULL), _parent(NULL), _dataIdx(dataIdx), _data(data)
{
readProperties();
rewind();
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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;
}
示例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);
//.........这里部分代码省略.........
示例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(¤tFiles);
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(¤tFiles);
/*free(currentFiles);*/
return TRUE;
}
示例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];
//.........这里部分代码省略.........
示例15: rewind
void CastleGame::seeker(char *sstring)
{
rewind(fptr);
while(fseeker(sstring) != FSUCCESS){}
}