void EXPRESSION() { if(TOKEN == plussym || TOKEN == minussym) { if(TOKEN == minussym) { GETTOKEN(); //OPR 0 1 printToFile(2,0,1); lines++; } else { GETTOKEN(); } } TERM(); while(TOKEN == plussym || TOKEN == minussym) { if(TOKEN == plussym) { GETTOKEN(); TERM(); printToFile(2,0,2); lines++; } else if(TOKEN == minussym) { GETTOKEN(); TERM(); printToFile(2,0,3); lines++; } } }
void CONDITION() { if(TOKEN == oddsym) { GETTOKEN(); EXPRESSION(); //OPR 0 6 printToFile(2,0,6); lines++; } else { EXPRESSION(); if(!isRelationalOperator(TOKEN)) { ERROR("Error number 20, relational operator expected."); } //In the enum, the tokens for logical operators are only +1 //from their corresponding OPR M value, so subtracting by one //should get the correct M value. int conditionValue = TOKEN-1; GETTOKEN(); EXPRESSION(); //OPR 0 M printToFile(2,0,conditionValue); lines++; } }
void FACTOR() { if(TOKEN == identsym) { symbol current = getSymbol(IDENTIFIER); if(current.kind == 2) { //LOD current.L current.M printToFile(3,0,current.addr); lines++; } else if(current.kind == 1) { //LIT 0 getSymbol().val printToFile(1,0,current.val); lines++; } else { ERROR("Error 21: expression must not contain a procedure identifier."); } GETTOKEN(); } else if(TOKEN == numbersym) { //LIT 0 NUMBER printToFile(1,0,NUMBER); lines++; GETTOKEN(); } else if(TOKEN == lparentsym) { GETTOKEN(); EXPRESSION(); if(TOKEN != rparentsym) { ERROR("Error number 22, right parenthesis missing."); } GETTOKEN(); } else { printf("%d\n", TOKEN); ERROR("Error number 23, the preceding factor cannot begin with this symbol."); } }
returnValue Matrix::printToFile( const char* const filename, const char* const name, PrintScheme printScheme ) const { FILE* file = 0; MatFile* matFile = 0; switch ( printScheme ) { case PS_MATLAB_BINARY: matFile = new MatFile; matFile->open( filename ); matFile->write( *this,name ); matFile->close( ); delete matFile; return SUCCESSFUL_RETURN; default: file = fopen( filename,"w+" ); if ( file == 0 ) return ACADOERROR( RET_FILE_CAN_NOT_BE_OPENED ); printToFile( file, name,printScheme ); fclose( file ); return SUCCESSFUL_RETURN; } }
int main() { initialize(); boundaries(); gaussSeidel(); printToFile(); }
//do arguments after file i/o main(int argc, char* argv[]){ int sizeOfArray=0; Student* array; FILE *filePointer; char* inputFile = malloc(argv[1]+1); char* outputFile= malloc(argv[2]+1); //if user didn’t supply enough input, terminate process if (argc != 3){ printf("No input file or output file.\n"); exit(1); } strcpy(inputFile, argv[1]); strcpy(outputFile, argv[2]); //open file filePointer = fopen(inputFile, "r"); if (filePointer == NULL) { fprintf(stderr, "Can't open input file \n"); exit(1); } //read the first line to get array size. fscanf(filePointer, "%d", &sizeOfArray); //read data array = readFile(sizeOfArray, filePointer); shuffle(array, sizeOfArray); //print results to outfile printToFile(array, outputFile, sizeOfArray); }
int main(int argc, char **argv) { if(argc < 2) { printf("Usage: %s forwarding_table_file\n\n", argv[0]); exit(0); } FILE *fp = fopen(argv[1], "r"); if(fp == NULL) { printf("Unable to open '%s'\n\n", argv[1]); exit(-1); } /* load the list file to a binary tree data structure */ node * tree = loadToTree(fp, argv); /* ORTC - step 1: discard interior next-hops */ clear_interior_next_hops(tree); /* ORTC - step 2: calculate most frequent next-hops by traversing bottom up */ percolate_tree(tree); /* ORTC - step 3: */ clean_redundancy(tree, NULL); /* print to file */ char destination[128]; sprintf(destination, "%s.compressed", argv[1]); FILE * destination_file = fopen(destination, "w"); if(fp == NULL) { printf("Unable to open '%s'\n\n", argv[1]); exit(-1); } printToFile(tree, destination_file); #ifdef DEBUG printf("final tree (pre-order traversal): "); print_tree(tree); puts("\n"); #endif destroy_tree(tree); LSTdestroy(queue, destroyItem); fclose(fp); fclose(destination_file); puts("done.\n"); exit(0); }
void printToFile(node * tree, FILE * destination_file) { list * queue_aux = queue; if (getItem(tree->interface_list) != -1) // if this node has a next-hop, write it to the file { queue_aux = queue; if(queue_aux == NULL) // still at root node, print '*' to simbolize default next-hop { fprintf(destination_file, "*\t%hd\n", *(short*)LSTgetitem(tree->interface_list)); } else { /* ugly hacks here to change LIFO to FIFO */ list * queue_fix_head = NULL; list * queue_fix = NULL; while(queue_aux != NULL) // not root, print the prefix (path taken) of the next-hop { queue_fix = LSTadd(queue_fix, makeItem(*(short*)LSTgetitem(queue_aux))); queue_aux = LSTfollowing(queue_aux); } queue_fix_head = queue_fix; while(queue_fix != NULL) // not root, print the prefix (path taken) of the next-hop { fprintf(destination_file, "%hd", *(short*)LSTgetitem(queue_fix)); queue_fix = LSTfollowing(queue_fix); } LSTdestroy(queue_fix_head, destroyItem); fprintf(destination_file, "\t%hd\n", *(short*)LSTgetitem(tree->interface_list)); // print the next-hop itself and change line } } // do the same for the rest of the tree if(tree->left != NULL) { queue = LSTadd(queue, makeItem(0)); printToFile(tree->left, destination_file); } if(tree->right != NULL) { queue = LSTadd(queue, makeItem(1)); printToFile(tree->right, destination_file); } // going back up, remove the last entered bit of the prefix queue = LSTremove(NULL, queue, destroyItem); }
void Pirata::robeNoRe(Tesoro treasure){ this->valor = 0; this->peso = 0; this->elementos = ""; int pesoSol = 0, valorSol = 0, tam = treasure.getTam(), i = 0, auxCapSaco = 0, capSaco = this->capSaco; string elementos = ""; Elemento * aux = NULL; Elemento ** arreglo = treasure.arreglo; sort(arreglo, tam); for (i; i < tam; i++){ if (arreglo[i]->getGramos() <= capSaco){ pesoSol += arreglo[i]->getGramos(); valorSol += arreglo[i]->getValor(); elementos += arreglo[i]->getID() + "\n"; capSaco = capSaco - arreglo[i]->getGramos(); auxCapSaco = capSaco; break; } } for (int j = i + 1; j < tam; j++){ if (arreglo[j]->getGramos() <= capSaco){ if (aux == NULL){ aux = arreglo[j]; auxCapSaco = capSaco - aux->getGramos(); } else{ if (auxCapSaco >= arreglo[j]->getGramos()){//Si cabe en el saco, lo meto pesoSol += aux->getGramos(); valorSol += aux->getValor(); elementos += aux->getID() + "\n"; capSaco = capSaco - aux->getGramos(); auxCapSaco = capSaco; aux = arreglo[j]; auxCapSaco = capSaco - aux->getGramos(); } else{//Si es mejor, reemplazo if (arreglo[j]->getValor() > aux->getValor()){ aux = arreglo[j]; auxCapSaco = capSaco - aux->getGramos(); } } } } } pesoSol += aux->getGramos(); valorSol += aux->getValor(); elementos += aux->getID() + "\n"; mejorRobo(pesoSol, valorSol, elementos); stringstream capSacoStr, pesoStr, valorStr; capSacoStr << this->capSaco; pesoStr << this->peso; valorStr << this->valor; printToFile("Capacidad del pirata: " + capSacoStr.str() + ", capacidad utilizada: " + pesoStr.str() + "\n" + "Ganancia obtenida: " + valorStr.str() + ", por el robo de: \n" + this->elementos + "\n\n", "robado-no-recursivo.txt"); }
void Pirata::robe(Tesoro treasure){ robeRe(treasure.arreglo, treasure.getTam(), 0, 0, 0, ""); stringstream capSacoStr, pesoStr, valorStr; capSacoStr << this->capSaco; pesoStr << this->peso; valorStr << this->valor; printToFile("Capacidad del pirata: " + capSacoStr.str() + ", capacidad utilizada: " + pesoStr.str() + "\n" + "Ganancia obtenida: " + valorStr.str() + ", por el robo de: \n" + elementos + "\n\n", "robado-recursivo.txt"); }
/** * Prints the binary tree to the database file. * @param tmpNode the current node being printed. * @param fp the file being written to. * @return void. **/ void printToFile(node *tmpNode, FILE *fp) { if (tmpNode == NULL) { fputc('\n', fp); return; } else if (tmpNode->question != NULL) { fputc('Q', fp); fputs(tmpNode->question, fp); fputc('\n', fp); } else if (tmpNode->animal != NULL) { fputc('A', fp); fputs(tmpNode->animal, fp); fputc('\n', fp); } printToFile(tmpNode->left, fp); printToFile(tmpNode->right, fp); }
/* Well, the name says all... */ void getNextToken(void) { PPARSEINFO pParseInfo=(PPARSEINFO)gScanner->user_data; //g_scanner_get_next_token(gScanner); getNextTokenFromStream(); setCurSymbolInfo(); printToFile(gScanner->token); }
void PROGRAM() { GETTOKEN(); BLOCK(); if(TOKEN != periodsym) { ERROR("Error number 9, period expected."); } //the halt at the end of the program printToFile(9, 0, 2); }
int generateData(Point *pointList, int amount, FILE *f) { int i; srand(time(NULL)); for(i = 0; i < amount; i++) { pointList[i].row = rand() % MAX_RANDOM_RANGE; pointList[i].col = rand() % MAX_RANDOM_RANGE; } printToFile(f, "%d %d\n", pointList, amount); return 0; }
/** * Handles the exiting of the program. * @param top the top, or root, of the binary tree. * @return void. **/ void quitAnimal(node *top) { int errNum; FILE *fp; fp = fopen("animals.db", "w"); printToFile(top, fp); if (fclose(fp) == EOF) { errNum = errno; fprintf(stderr, "Error closing file: %s\n", strerror(errNum)); } }
void TERM() { FACTOR(); while(TOKEN == multsym || TOKEN == slashsym) { if(TOKEN == multsym) { GETTOKEN(); FACTOR(); //OPR 0 4 printToFile(2,0,4); lines++; } else if(TOKEN == slashsym) { GETTOKEN(); FACTOR(); //OPR 0 5 printToFile(2,0,5); lines++; } } }
int main() { SoundPlayer soundPlayer = SoundPlayer(); Mp3Decoder mp3Decoder = Mp3Decoder(); MicRecorder micRecorder = MicRecorder(); unsigned char buffer[BUFSIZE*50] = {}; unsigned char recBuffer[BUFSIZE*50] = {}; // Put path to file here std::string path = "smw_coin.mp3"; // TODO: Manage more than int16_t encoding format, mono and 44.1kHz Mp3Format mp3Format = mp3Decoder.Open(path); //std::cout << "encoding: " << mp3Format.encoding << std::endl; //std::cout << "channels: " << mp3Format.channels << std::endl; //std::cout << "rate: " << mp3Format.rate << std::endl; int decodeNumber = 0; int decodedQty = 0; while ((decodedQty = mp3Decoder.Decode(buffer+decodeNumber*BUFSIZE, BUFSIZE)) > 0) { soundPlayer.Play(buffer+decodeNumber*BUFSIZE, decodedQty); // Record some data in the buffer micRecorder.Record(recBuffer+decodeNumber*BUFSIZE, decodedQty); decodeNumber++; } unsigned int samplesQty = (decodeNumber-1)*BUFSIZE/sizeof(int16_t)+decodedQty; mp3Decoder.Close(); // Process the signals as wanted here int delay = SignalProcessor::GetDelay((int16_t*)buffer, (int16_t*)recBuffer, samplesQty); SignalProcessor::Delay((int16_t*)buffer, samplesQty, delay); SignalProcessor::Scale((int16_t*)buffer, samplesQty, 1, 2); SignalProcessor::Subtract((int16_t*)recBuffer, (int16_t*)buffer, samplesQty); // Play back for more fun for (unsigned int i = 0; i < decodeNumber; i++) { soundPlayer.Play(recBuffer+i*BUFSIZE, BUFSIZE); } printToFile(samplesQty, {(int16_t*)buffer, (int16_t*)recBuffer}); }
/************************************************************************ method CompilerTrackingInfo::logCompilerStatusOnInterval Dump the fields of this class out to a file (or to repository) if the tracking compiler interval has expired ************************************************************************/ void CompilerTrackingInfo::logCompilerStatusOnInterval(Int32 intervalLengthMins) { if( intervalExpired(intervalLengthMins) ) { // // this interval is now done/expired endIntervalTime_ = getCurrentTimestamp(); // // get the latest cache stats once per interval if (!CURRENTQCACHE->getCompilationCacheStats(currentQCacheStats_)) { // if query is disabled, clear the cache counters clearQCacheCounters(); } // // log this interval if( NULL != getCompilerTrackingLogFilename() ) { printToFile(); } // // log directly to a private table using dynamic SQL // instead of using the Repository infrastructure to // populate repository table if (CmpCommon::getDefault(COMPILER_TRACKING_LOGTABLE) == DF_ON) { logIntervalInPrivateTable(); } // // This table doesn't exist on Windows, so don't log there // always log to the repository table Int32 rc = logIntervalInRepository(); if (rc) { // raise a warning that compiler process is unable to log // its status and health information to the repository *CmpCommon::diags() << DgSqlCode(2242); } // // since the interval is expired, reset to begin tracking new interval resetInterval(); } }
PrintDialog::PrintDialog(QWidget *parent, Firmware * firmware, GeneralSettings & generalSettings, ModelData & model, const QString & filename) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), firmware(firmware), generalSettings(generalSettings), model(model), printfilename(filename), ui(new Ui::PrintDialog), multimodelprinter(firmware) { ui->setupUi(this); setWindowIcon(CompanionIcon("print.png")); setWindowTitle(model.name); multimodelprinter.setModel(0, model); ui->textEdit->setHtml(multimodelprinter.print(ui->textEdit->document())); if (!printfilename.isEmpty()) { printToFile(); QTimer::singleShot(0, this, SLOT(autoClose())); } }
void PageRunner::reallyFinished() { int latency = time.restart(); // err << latency << " " << changed << " " << nam->hasOutstandingRequests() << endl; if (changed || latency >= 152 || nam->hasOutstandingRequests()) { QTimer::singleShot(150, this, SLOT(reallyFinished())); changed = false; return; } if (!exportpdf.isEmpty() || !exportpng.isEmpty()) { setViewportSize(mainFrame()->contentsSize()); } if (!exportpng.isEmpty()) { renderToFile(exportpng); } if (!exportpdf.isEmpty()) { printToFile(exportpdf); } qApp->exit(sawJSError); }
returnValue VectorspaceElement::printToFile( const char* const filename, const char* const name, const char* const startString, const char* const endString, uint width, uint precision, const char* const colSeparator, const char* const rowSeparator ) const { FILE* file = fopen( filename,"w+" ); if ( file == 0 ) return ACADOERROR( RET_FILE_CAN_NOT_BE_OPENED ); printToFile( file, name,startString,endString,width,precision,colSeparator,rowSeparator ); fclose( file ); return SUCCESSFUL_RETURN; }
/************************************************************************ method CompilerTrackingInfo::logCompilerStatusOnInterval Dump the fields of this class out to a file (or to repository) if the tracking compiler interval has expired ************************************************************************/ void CompilerTrackingInfo::logCompilerStatusOnInterval(Int32 intervalLengthMins) { if( intervalExpired(intervalLengthMins) ) { // // this interval is now done/expired endIntervalTime_ = getCurrentTimestamp(); // // get the latest cache stats once per interval if (!CURRENTQCACHE->getCompilationCacheStats(currentQCacheStats_)) { // if query is disabled, clear the cache counters clearQCacheCounters(); } // // log this interval if( NULL != getCompilerTrackingLogFilename() ) { printToFile(); } // // log directly to a private table using dynamic SQL if (CmpCommon::getDefault(COMPILER_TRACKING_LOGTABLE) == DF_ON) { logIntervalInPrivateTable(); } // always log to log4cxx log logIntervalInLog4Cxx(); // since the interval is expired, reset to begin tracking new interval resetInterval(); } }
void printNode(struct a_NODE * node_p) { FILE *pfile; if(node_p) { struct a_NODE node_ = *node_p; switch(node_.token) { // TOKENS case LIT_TRUE: printToFile(pfile,(node_.node)->value); break; case LIT_FALSE: printToFile(pfile,(node_.node)->value); break; case LIT_INTEGER: printToFile(pfile,(node_.node)->value); break; case TK_IDENTIFIER: printToFile(pfile,(node_.node)->value); break; case LIT_CHAR: printToFile(pfile,"'"); printToFile(pfile,(node_.node)->value); printToFile(pfile,"'"); break; case LIT_STRING: printToFile(pfile,"\""); printToFile(pfile,(node_.node)->value); printToFile(pfile,"\""); break; // LIST case LIST: printNode((node_.sons[0])); if((node_.sons[1])!=NULL) { printToFile(pfile," "); printNode((node_.sons[1])); } break; // TYPE case KW_BOOL: printToFile(pfile,"bool "); break; case KW_WORD: printToFile(pfile,"word "); break; case KW_BYTE: printToFile(pfile,"byte "); break; // FUNC_DECLARATION case ARGUMENTS: printNode((node_.sons[0])); printNode((node_.sons[1])); if((node_.sons[2])!=NULL) { printToFile(pfile,","); printNode((node_.sons[2])); } break; case D_NODE: // GAMBIARRATION if((node_.sons[0])!=NULL) printNode((node_.sons[0])); printNode((node_.sons[1])); break; case FUNC_DECLARATION: printNode((node_.sons[0])); printNode((node_.sons[1])); printToFile(pfile,"("); if((node_.sons[2])!=NULL) printNode((node_.sons[2])); printToFile(pfile,")"); printNode((node_.sons[3])); // SEMPRE D_NODE , GAMBIARRATIONN break; // DECLARATIONS case PROG: printNode((node_.sons[0])); //printToFile(pfile,";"); if((node_.sons[1])!=NULL) printNode((node_.sons[1])); break; case DECLARATION: printNode((node_.sons[0])); printNode((node_.sons[1])); printToFile(pfile,":"); printNode((node_.sons[2])); printToFile(pfile,";"); break; case DECLARATION_POINTER: printNode((node_.sons[0])); printToFile(pfile,"$"); printNode((node_.sons[1])); printToFile(pfile,":"); printNode((node_.sons[2])); printToFile(pfile,";"); break; case DECLARATION_VEC: printNode((node_.sons[0])); printNode((node_.sons[1])); printToFile(pfile,"["); printNode((node_.sons[2])); printToFile(pfile,"]"); printToFile(pfile,";"); break; case DECLARATION_VEC_INIT: printNode((node_.sons[0])); printNode((node_.sons[1])); printToFile(pfile,"["); printNode((node_.sons[2])); printToFile(pfile,"]"); printToFile(pfile,":"); printNode((node_.sons[3])); printToFile(pfile,";"); break; // EXPRESSION case '&': printToFile(pfile,"&"); printNode((node_.sons[0])); break; case POINTER: printToFile(pfile,"*"); printNode((node_.sons[0])); break; case '*': //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"*"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case '(': printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,")"); break; case '+': //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"+"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case '-': //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"-"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case '/': //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"/"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case OR: //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"||"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case AND: //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"&&"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case LE: //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"<="); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case EQ: //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"=="); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case GE: //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,">="); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case NE: //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"!="); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case '>': //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,">"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case '<': //printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,"<"); printNode((node_.sons[1])); //printToFile(pfile,")"); break; case VECCALL: printNode((node_.sons[0])); printToFile(pfile,"["); printNode((node_.sons[1])); printToFile(pfile,"]"); break; case NORMAL: printNode((node_.sons[0])); // FUNCALL ARGCALL CMD_SEQ break; case FUNCALL: printNode((node_.sons[0])); printToFile(pfile,"("); if((node_.sons[1])!=NULL) printNode((node_.sons[1])) ; printToFile(pfile,")"); break; case ARGCALL: printNode((node_.sons[0])); if(node_.sons[1]!=NULL) { printToFile(pfile,","); printNode((node_.sons[1])); } break; case CMD_SEQ: printNode((node_.sons[0])); printToFile(pfile,";"); if(node_.sons[1]!=NULL) { printNode((node_.sons[1])); } break; // OUTPUT case OUTPUT_L: printNode((node_.sons[0])); if(node_.sons[1]!=NULL) { printToFile(pfile,","); printNode((node_.sons[1])); } break; // CMD case INPUT: printToFile(pfile,"input "); printNode((node_.sons[0])); printToFile(pfile," "); break; case OUTPUT: printToFile(pfile,"output "); printNode((node_.sons[0])); printToFile(pfile," "); break; case RETURN: printToFile(pfile,"return "); printNode((node_.sons[0])); printToFile(pfile," "); break; case BLOCK: printToFile(pfile,"{"); printNode((node_.sons[0])); printToFile(pfile,"}"); printToFile(pfile," "); break; case '=': printNode((node_.sons[0])); printToFile(pfile,"="); printNode((node_.sons[1])); printToFile(pfile," "); break; case IF_THEN: printToFile(pfile,"if("); printNode((node_.sons[0])); printToFile(pfile,")then "); printNode((node_.sons[1])); printToFile(pfile," "); break; case IF_THEN_ELSE: printToFile(pfile,"if("); printNode((node_.sons[0])); printToFile(pfile,")then "); printNode((node_.sons[1])); printToFile(pfile,"else "); printNode((node_.sons[2])); printToFile(pfile," "); break; case LOOP : printToFile(pfile,"loop"); printToFile(pfile,"("); printNode((node_.sons[0])); printToFile(pfile,")"); printNode((node_.sons[1])); printToFile(pfile," "); break; // DEFAULT default: printToFile(pfile,"DEFAULT"); break; } // switch } // if node }
void printToFile(node_t * tree,FILE *output) { if(tree->left) printToFile(tree->left,output); fprintf(output,"%s\n",tree->val); if(tree->right) printToFile(tree->right,output); }
int main(int argc, char **argv) { node_t * curr; tree_info root; mergelist *mergeroot,*mergetemp,*mergecurrent,*mergeprev; int i,j; char *word; char *searchString; // int wordLength; long long fileSize; long long currFileSize; int fileCount; long long fileOffset; long long low, prevlow, high,prevhigh, mid ; int numiterations; char alphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char *tempFileName; FILE *input, *output; fileCount=0; if(argc != 4) { printf(" Usage : %s <inputfile> <searchstring> <numiterations>",argv[0]); return -1; } searchString = argv[2]; numiterations = atol(argv[3]); input = fopen(argv[1],"r"); if(!input) { printf("Failed to open input file"); return -1; } fseek(input,0,SEEK_END); fileSize = ftell(input); printf("filesize = %d\n",fileSize); fseek(input,0,SEEK_SET); i=0; low=0; high = fileSize-1; while(1) { int templow; int temphigh; mid=(low+high)/2; printf("low =%lld, high = %lld, mid = %lld , high - low =%lld, high - mid = %lld\n", low,high, mid, high -low, high -mid); fseek(input,mid,SEEK_SET); word=readInputFile(input); templow = mid+strlen(word); free(word); word = readInputFile(input); temphigh = templow+strlen(word); if(high -mid <strlen(word)) { break; } /**if(ftell(input) >high) { free(word); fseek(input,low,SEEK_SET); while(ftell(input)<=high) { word = readInputFile(input); if(word!=NULL) { printf("Processed %s\n",word); free(word); } } word = readInputFile(input); if(word!=NULL) { printf("Processed %s\n",word); free(word); } word = readInputFile(input); if(word!=NULL) { printf("Processed %s\n",word); free(word); } break; }**/ if(word!=NULL) { printf("%s\n",word); prevhigh = high; prevlow = low; if(strcmp(searchString,word) < 0) { high=temphigh; } else { low=templow; } free(word); } if((high==prevhigh)&&(low==prevlow)) { break; } i++; if(i==numiterations) { break; } } fseek(input,low,SEEK_SET); word = readInputFile(input); printf("Processed %s\n",word); free(word); word = readInputFile(input); printf("Processed %s\n",word); free(word); word = readInputFile(input); printf("Processed %s\n",word); free(word); fclose(input); return -1; grandTotalTreeNodes=0; grandTotalTreeSize=0;; while(!feof(input)) { tempFileName=(char *)malloc(strlen(argv[4])+1+strlen(argv[3])+4+1); sprintf(tempFileName,"%s\\%s.%d",argv[4],argv[3],fileCount+1); printf("%s",tempFileName); output = fopen(tempFileName,"w"); if(!output) { printf("Failed to open output file"); return -1; } root.node = NULL; root.treeMemSize =0; totalTreeSize = 0; totalTreeNodes =0; while(totalTreeSize <fileSize) { curr = (node_t *)malloc(sizeof(node_t)); if(!curr) { printf("Failed to allocate memory 1"); return -1; } curr->left = curr->right = NULL; if((word=readInputFile(input)) !=NULL) { curr->val = word; insert(&(root.node), curr); } else { break; } } // } root.treeMemSize = totalTreeSize; root.treeNumNodes = totalTreeNodes; printToFile(root.node,output); printf("In freemem \n"); freemem(root.node); printf("Total treesize = %d\n",root.treeMemSize); printf("Total treenodes = %d\n",root.treeNumNodes); grandTotalTreeNodes+=totalTreeNodes; grandTotalTreeSize+=totalTreeSize; free(tempFileName); fileCount++; fclose(output); } printf("Grand Total treesize = %d\n",grandTotalTreeSize); printf("Gran Total treenodes = %d\n",grandTotalTreeNodes); fclose(input); mergeroot=NULL; grandTotalTreeNodes=0; for(i=0;i<fileCount;i++) { mergetemp=(mergelist *)malloc(sizeof(mergelist)); tempFileName=(char *)malloc(strlen(argv[4])+1+strlen(argv[3])+4+1); sprintf(tempFileName,"%s\\%s.%d",argv[4],argv[3],i+1); mergetemp->input = fopen(tempFileName,"r"); if(!mergetemp->input) { printf("Failed to open input file"); return -1; } mergetemp->val=readInputFile(mergetemp->input); mergetemp->isFinished=0; mergetemp->next=mergeroot; mergeroot=mergetemp; } output = fopen(argv[2],"w"); if(!output) { printf("Failed to open output file"); return -1; } while(1) { mergetemp=mergeroot; mergecurrent=NULL; mergeprev=NULL; while(mergetemp!=NULL) { if(mergetemp->isFinished==1) { mergetemp=mergetemp->next; continue; } if(mergetemp->val !=NULL) { if(mergecurrent==NULL) { mergecurrent=mergetemp; } else if(strcmp(mergetemp->val,mergecurrent->val)<0) { mergeprev = mergecurrent; mergecurrent=mergetemp; } } else { mergetemp->isFinished = 1; fclose(mergetemp->input); } mergetemp=mergetemp->next; } if(mergecurrent==NULL) { break; } else { while((mergeprev==NULL||strcmp(mergecurrent->val,mergeprev->val)<0)&&mergecurrent->val!=NULL) { fprintf(output,"%s\n",mergecurrent->val); grandTotalTreeNodes+=1; mergecurrent->val=readInputFile(mergecurrent->input);; } } } printf("Gran Total treenodes after merge= %d\n",grandTotalTreeNodes); fclose(output); }
void BLOCK() { if(TOKEN == constsym) { do { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 4, const must be followed by identifier."); } GETTOKEN(); if(TOKEN == becomessym) { ERROR("Error number 1, use = instead of :="); } if(TOKEN != eqlsym) { ERROR("Error number 2, identifier must be followed by ="); } GETTOKEN(); if(TOKEN != numbersym) { ERROR("Error number 3, = must be followed by a number."); } ENTER(1); GETTOKEN(); } while(TOKEN == commasym); if(TOKEN != semicolonsym) { ERROR("Error number 5, semicolon or comma missing."); } GETTOKEN(); } if(TOKEN == varsym) { do { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 4, var must be followed by identifier."); } ENTER(2); GETTOKEN(); } while(TOKEN == commasym); if(TOKEN != semicolonsym) { ERROR("Error number 5, semicolon or comma missing."); } GETTOKEN(); } //procedure section (will not be used in module 3) while(TOKEN == procsym) { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 4, procedure must be followed by identifier."); } ENTER(3); GETTOKEN(); if(TOKEN != semicolonsym) { ERROR("Error number 6, incorrect symbol after procedure declaration."); } GETTOKEN(); BLOCK(); if(TOKEN != semicolonsym) { //may need to be a different error message ERROR("Error number 5, semicolon or comma missing."); } GETTOKEN(); } //INC O (4+numOfVariables) printToFile(6,0,4+numOfVariables); lines++; STATEMENT(); }
void STATEMENT() { //initialization if(TOKEN == identsym) { //stores the name of the identifier that will be initialized char name[12]; strcpy(name, IDENTIFIER); //if identifier is not a variable, produce error if(getSymbol(IDENTIFIER).kind != 2) { ERROR("Error number 12, assignment to constant or procedure not allowed."); } GETTOKEN(); if(TOKEN != becomessym) { ERROR("Error number 13, assignment operator expected."); } GETTOKEN(); EXPRESSION(); symbol current = getSymbol(name); //STO 0 M printToFile(4,current.level,current.addr); lines++; } //procedure call (not in tiny PL/0) else if(TOKEN == callsym) { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 14, call must be followed by an identifier."); } //if the identifier is not a procedure, produce an error if(getSymbol(IDENTIFIER).kind != 3) { ERROR("Error number 15, call of a constant or variable is meaningless."); } GETTOKEN(); } //a group of statements else if(TOKEN == beginsym) { GETTOKEN(); STATEMENT(); while(TOKEN == semicolonsym) { GETTOKEN(); STATEMENT(); } if(TOKEN != endsym) { ERROR("Error number 26, end is expected."); } GETTOKEN(); } else if(TOKEN == ifsym) { GETTOKEN(); CONDITION(); //top of the stack has whether it is true or false if(TOKEN != thensym) { ERROR("Error number 16, then expected."); } //after the condition, count how many instructions are written int currentLines = lines; inConditional++; fpos_t filePos; fgetpos(ifp, &filePos); //loop ensures this is done twice int i; for(i = 0; i < 2; i++) { if(i == 1) { inConditional--; //make branch here (lines contains the line that you jump to if the condition is not met) //printToFile() //JPC 0 M = lines printToFile(8,0,lines); //returns the file to the previous position fsetpos(ifp, &filePos); lines = currentLines; //Lines increment for prinToFile used in for loop //lines++; } lines++; GETTOKEN(); STATEMENT(); } } else if(TOKEN == whilesym) { int jumpBackLine = lines; GETTOKEN(); CONDITION(); //top of the stack has whether it is true or false if(TOKEN != dosym) { ERROR("Error number 18, do expected."); } //after the condition, count how many instructions are written int currentLines = lines; inConditional++; fpos_t filePos; fgetpos(ifp, &filePos); //loop ensures this is done twice int i; for(i = 0; i < 2; i++) { if(i == 1) { inConditional--; //make branch here (lines + 1 contains the line that you jump to if the condition is not met) //printToFile() //JPC 0 M = l printToFile(8,0,lines + 1); //returns the file to the previous position fsetpos(ifp, &filePos); lines = currentLines; //Lines increment for the printToFile used in for loop //lines++; } //the line for the branch is added lines++; GETTOKEN(); STATEMENT(); } //JMP 0 M = jumpBackLines printToFile(7,0,jumpBackLine); lines++; } }
void BLOCK(int enterIntoTable) { lexiLevel++; if(TOKEN == constsym) { do { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 4, const must be followed by identifier."); } GETTOKEN(); if(TOKEN == becomessym) { ERROR("Error number 1, use = instead of :="); } if(TOKEN != eqlsym) { ERROR("Error number 2, identifier must be followed by ="); } GETTOKEN(); if(TOKEN != numbersym) { ERROR("Error number 3, = must be followed by a number."); } if(enterIntoTable == 0) { ENTER(1); } GETTOKEN(); } while(TOKEN == commasym); if(TOKEN != semicolonsym) { ERROR("Error number 5, semicolon or comma missing."); } GETTOKEN(); } if(TOKEN == varsym) { do { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 4, var must be followed by identifier."); } if(enterIntoTable == 0) { ENTER(2); } GETTOKEN(); } while(TOKEN == commasym); if(TOKEN != semicolonsym) { ERROR("Error number 5, semicolon or comma missing."); } GETTOKEN(); } while(TOKEN == procsym) { GETTOKEN(); if(TOKEN != identsym) { ERROR("Error number 4, procedure must be followed by identifier."); } if(enterIntoTable == 0) { ENTER(3); } GETTOKEN(); if(TOKEN != semicolonsym) { ERROR("Error number 6, incorrect symbol after procedure declaration."); } //saves the current position, for the jmp statement int currentLines = lines; inConditional++; fpos_t filePos; fgetpos(ifp, &filePos); int i; for(i = 0; i < 2; i++) { if(i == 1) { inConditional--; //JMP 0 M = lines printToFile(7,0,lines); //returns the file to the previous position fsetpos(ifp, &filePos); lines = currentLines; } lines++; GETTOKEN(); BLOCK(i+enterIntoTable); //return from the procedure call printToFile(2, 0, 0); lines++; } //semicolon is needed after a procedure if(TOKEN != semicolonsym) { //may need to be a different error message ERROR("Error number 5, semicolon or comma missing."); } GETTOKEN(); } //INC O (4+numOfVariables) printToFile(6,0,4+numOfVariablesInLexiLevel()); lines++; STATEMENT(); lexiLevel--; }
void GenWordList::sortAllWords(vector<Page>& pages){ cout<<"pages.size = "<< pages.size()<<endl; for(int i = 0; i < pages.size(); i++){ Parser *ps = new Parser(pages[i].page.length()); //buffer = NULL; //cout << i << endl; //cout <<pages[i].page<<endl; //buffer = (char*)malloc(sizeof(char)*pages[i].page.length()); char buffer[pages[i].page.length()]; strcpy(buffer,pages[i].page.c_str()); unsigned int res = ps->parser(buffer, pages[i].len); // cout<<"i="<<i<<" page_docId: "<<pages[i].docId << " res= "<<res<<endl; if (res > 0){ string resBuffer = ps->getBuf(); vector<int> pos = ps->getPos(); //cout<<"buffer length = "<<buffer.length()<<endl; //cout<<"pos size = "<< pos.size()<<endl; storeDocInfo(pages[i].docId, pages[i].url,pos.size()); string word = ""; int k = 0; for(int j = 0; j < resBuffer.length(); j++){ //cout<<"k="<<k<<endl; if(resBuffer[j] == ' '){ if(word == "") continue; map<string,list<Post>>::iterator it = word_by_alphabet.find(word); if(it == word_by_alphabet.end() || it->second.back().previousDocId != pages[i].docId){ //docId for new post, freqency, previous pos,previous docId; Post post(pages[i].docId,1,pos[k],pages[i].docId); post.pos.push_back(pos[k++]); if(it == word_by_alphabet.end()){ list<Post> tmpList; tmpList.push_back(post); word_by_alphabet.insert(pair<string,list<Post>>(word, tmpList)); } else{ post.docId -= it->second.back().previousDocId; it->second.back().previousDocId = pages[i].docId; it->second.push_back(post); } } else{ it->second.back().freq ++; it->second.back().pos.push_back(pos[k] - it->second.back().previousPos); it->second.back().previousPos = pos[k++]; } //cout<<word<<endl; word = ""; } else if(resBuffer[j] == '\n'){ word = ""; } else{ word += resBuffer[j]; } } } //ps->resetBuf(); //ps->resetPos(); delete ps; } cout<<"here "<<word_by_alphabet.size()<<endl; printToFile(); //delete ps; return; }
JNIEXPORT void JNICALL Java_sun_misc_MessageUtils_toStdout(JNIEnv *env, jclass cls, jstring s) { printToFile(env, s, stdout); }