void ReadInitFile(char *SubWatershedFileName, LISTPTR * Input, char* CustomConfig) { FILE *SubWatershedFile = NULL;/*File with watershed specific info*/ FILE *InFile = NULL; /* File with generic input information */ char Buffer[BUFSIZE + 1]; /* Tempora */ int i; /* counter */ int NLines; /* Number of lines in the input file */ LISTPTR Current = NULL; /* pointer to current node in list */ LISTPTR Head = NULL; /* pointer to the start of the list */ char buffer[40]; sprintf(buffer, "..\\config\\basins\\%s",SubWatershedFileName); OpenFile(&SubWatershedFile, (char *) buffer, "r", FALSE); NLines = CountLines(SubWatershedFile); rewind(SubWatershedFile); for (i = 0; i < NLines; i++) { fgets(Buffer, BUFSIZE, SubWatershedFile); Strip(Buffer); if (IsSection(Buffer) || IsKeyEntryPair(Buffer)) { if (Head == NULL) { Head = CreateNode(); Current = Head; *Input = Head; } else { Current->Next = CreateNode(); Current = Current->Next; } strncpy(Current->Str, Buffer, BUFSIZE); } } fclose(SubWatershedFile); //use two part config files- info common to all subbasins in ConFigFileName if(CustomConfig==NULL)strcpy(CustomConfig,"base"); OpenFile(&InFile, (char *) CustomConfig, "r", FALSE); printf("Using config info from file: %s \n\n", CustomConfig); NLines = CountLines(InFile); rewind(InFile); for (i = 0; i < NLines; i++) { fgets(Buffer, BUFSIZE, InFile); strcpy(Buffer,replace(Buffer,"<basin>",SubWatershedFileName)); strcpy(Buffer,replace(Buffer,"<condition>",CustomConfig)); Strip(Buffer); if (IsSection(Buffer) || IsKeyEntryPair(Buffer)) { if (Head == NULL) { Head = CreateNode(); Current = Head; *Input = Head; } else { Current->Next = CreateNode(); Current = Current->Next; } strncpy(Current->Str, Buffer, BUFSIZE); } }//for i == 0 to nlines fclose(InFile); return; }
void FormatText::PushTextWrapped( FTTextureFont* font, float x, float y, const char* text, const Vector& colour, AlignX::Enum alignX, AlignY::Enum alignY, float maxwidth) { float ignore = -1; float yOffset = 0; if(alignY == AlignY::Bottom) { float lines = (float) CountLines(font, text, maxwidth, &ignore) - 1; yOffset = ((float)lines) * FormatText::GetFaceMaxHeight(font); } else if(alignY == AlignY::Center) { float lines = (float) CountLines(font, text, maxwidth, &ignore) - 1; lines *= 0.5; float lineHeight = FormatText::GetFaceMaxHeight(font); yOffset = (lines * lineHeight) - lineHeight*0.25; } else { yOffset = -GetFaceMaxHeight(font) * 0.75; } int lineEnd = 0; do { int outStart = 0; float outPixelWidth = 0; //dsprintf("\tNextline cursor[%d] char[%c]\n", lineEnd, text[lineEnd]); NextLine(font, text, lineEnd, maxwidth, &outStart, &lineEnd, &outPixelWidth); //dsprintf("Output: outStart[%d] outFinish[%d], outPixelWidth[%f]\n", // outStart, lineEnd, outPixelWidth); float xPos = x; if(alignX == AlignX::Right) { xPos -= outPixelWidth; } else if(alignX == AlignX::Center) { xPos -= outPixelWidth / 2; } RenderLine(font, xPos, y + yOffset, text, outStart, lineEnd); y = y - GetFaceMaxHeight(font); } while (text[lineEnd] != '\0'); return; }
int main() { char *filename = new char[100]; std::strcpy(filename,"out.txt"); int count = CountLines(filename); std::string first = ReturnString(filename,0); for (int i = 1;i < count;i ++) { std::string second = ReturnString(filename,count - i); char *buf = new char[1000000000]; std::strcpy(buf,second.c_str()); char *ptrn = new char[1000000000]; std::strcpy(ptrn,first.c_str()); int blen = strlen(buf); int plen = strlen(ptrn); int *skip = MakeSkip(ptrn,plen); int *shift = MakeShift(ptrn,plen); int result = BMSearch(buf, blen, ptrn, plen, skip, shift); printf("%d\t", result); delete []buf; delete []ptrn; } return 0; }
void AllShowingTextView::FrameResized(float width, float height) { float minHeight = TextHeight(0, CountLines() - 1); SetExplicitMinSize(BSize(B_SIZE_UNSET, minHeight)); BTextView::FrameResized(width, minHeight); }
GUTF8String UnicodeByteStream::gets( size_t const t,unsigned long const stopat,bool const inclusive) { GUTF8String retval; unsigned int len=buffer.length()-bufferpos; if(!len) { int i; char *buf; static const size_t bufsize=327680; GPBuffer<char> gbuf(buf,bufsize); while((i=read(buf,bufsize)>0)) { if((len=buffer.length()-bufferpos)) break; } } if(len) { int i=buffer.search((char)stopat,bufferpos); if(i>=0) { if(inclusive) { ++i; } if(t&&(i>(int)t+bufferpos)) { i=t+bufferpos; } if(i>bufferpos) { retval=buffer.substr(bufferpos,i-bufferpos); } bufferpos=i; linesread+=CountLines(retval); }else { retval=buffer.substr(bufferpos,len); bufferpos=buffer.length(); linesread+=CountLines(retval); retval+=gets(t?(t-(i-bufferpos)):0,stopat,inclusive); } } return retval; }
Text::Text(char *text, size_t length) { ASSERT(text != NULL); ASSERT(length > 0); m_text = text; m_length = length; m_numLines = CountLines(); }
void AllShowingTextView::GetHeightForWidth(float width, float* min, float* max, float* preferred) { BTextView::GetHeightForWidth(width, min, max, preferred); float minHeight = TextHeight(0, CountLines() - 1); if (min) *min = minHeight; }
void HTMLView::AddStatement() { int32 number_of_runs = (int32)insertStyles.Count(); int32 lineCount, lastOffset; bool doAutoScroll = true; // Get the scrollbar position... this is the part where we do autoscroll, but only // if the scrollbar is already at the bottom. That way it won't get annoying. if( scroll == NULL ) scroll = ScrollBar( B_VERTICAL ); if( scroll ) { float scrMin, scrMax; scroll->GetRange( &scrMin, &scrMax ); if( scroll->Value() != scrMax ) doAutoScroll = false; } // allocate some room for the text_run_array text_run_array* styles = (text_run_array*)malloc( sizeof(text_run_array) + (sizeof(text_run) * (number_of_runs - 1))); // fill in the individual text_runs styles->count = number_of_runs; for( int32 i = 0; i < number_of_runs; ++i ) styles->runs[i] = insertStyles[i]; // Get the offset of the last line lineCount = CountLines(); lastOffset = OffsetAt( lineCount ); // Add the silly thing Insert( lastOffset, insertText, strlen(insertText), styles ); // do the autoscroll, if needed if( doAutoScroll ) { lineCount = CountLines(); lastOffset = OffsetAt( lineCount ); ScrollToOffset( lastOffset ); } // Prepare to start over Empty = false; ClearFontStates(); free( styles ); }
void TestTxtTools(void) { char FileName [] = "test.txt" unsigned int numLines; unsigned int numWords; numLines = CountLines(FileName); numWords = CountEnglishWords(FileName); printf("%u %u\n",numLines,numWords); }
void TexView::GoToLine(int32 index) { if(index < 0 || index > CountLines() || TextLength() <= 0) return; vector<int> eols; vector<int> sols; FillSolEol(sols,eols,0,TextLength()-1); Select(sols[index],eols[index]); }
int main() { printf ("# Program by Shulgin E." "\n\n"); //setlocale (LC_ALL, "Russian"); // If u want to sort a russian poem char FilePath[MAXFILEPATH] = "Bayrone.txt"; char ReadMode[MAXREADMODE] = "rb"; FILE* InputFile = FileOpen (FilePath, ReadMode); if (InputFile == PTR_ERROR) return -1; long long file_len = FileLength (InputFile); if (file_len == INT_ERROR) return -1; char* buffer = FileBuffer (InputFile, file_len); fclose (InputFile); if (buffer == PTR_ERROR) return -1; //printf ("\n--------------\n" "<%s>" "\n--------------\n", buffer); /*const char* bufCopy = (char*) calloc (file_len, sizeof(*buffer)); memcpy(buffer, bufCopy, sizeof(buffer)); printf("\n<%s>\n", bufCopy); */ int nLines = 0; nLines = CountLines (buffer, file_len); if (nLines == INT_ERROR) return -1; //printf ("nLines = %d" "\n", nLines); my_string* text = (my_string*) calloc (nLines, sizeof(my_string*)); Text_Construct (text, buffer, file_len, nLines); TextOut (text, nLines); int SortType = 1; printf ("Available types of sort:" "\n" " 1) SortFromBeg" "\n" " 2) SortFromEnd" "\n"); printf ("Input number of preferred sorting: "); scanf ("%d", &SortType); int sort_check = TextSort (SortType, text, nLines); if (sort_check == INT_ERROR) return -1; printf ("\n" "Sorted text:" "\n"); TextOut (text, nLines); int Text_check = Text_Destruct (text, nLines); if (Text_check == INT_ERROR) return -1; int Buf_check = FreeBuffer (buffer); if (Buf_check == INT_ERROR) return -1; return 1; }
ProjectCodeStats CodeStatExecDlg::ParseProject(int index, ParsedFileNamesSet *parsedFileNames) { ProjectCodeStats stat; cbProject* project = Manager::Get()->GetProjectManager()->GetProjects()->Item(index - 1); stat.numFiles = project->GetFilesCount(); for (int i = 0 ; i < stat.numFiles; ++i) { ProjectFile* pf = project->GetFile(i); wxFileName filename(pf->file.GetFullPath(), wxPATH_DOS); if (parsedFileNames) { if (parsedFileNames->find(filename.GetFullPath())==parsedFileNames->end()) parsedFileNames->insert(filename.GetFullPath()); else continue; } if (!filename.FileExists()) ++stat.numFilesNotFound; else { // Find the language associated to the file extension int language = -1; for (int l = 0; l < m_numLanguages; ++l) { for (int j = 0; j < (int)m_languages[l].ext.Count(); ++j) { if (filename.GetExt() == m_languages[l].ext[j]) { language = l; break; } } } // If the language is found, analyse the source file if (language > -1) CountLines(stat, filename, m_languages[language]); else ++stat.numSkippedFiles; } if (stat.numFiles > 1) { ++m_currentFile; UpdateProgress(); } } return stat; }
//----------------------------------------------------------- // main( int argc, char **argv ) // // Purpose: // Execute all of the functions for the homework assigment. // // Parameters: // int argc the number of arguments passed in // char **argv array of arguments; first argument is a // filename // // Returns: // int 0 // // // Method: // Execute each function. Pass the filename to the functions // that need it. // //----------------------------------------------------------- int main( int argc, char **argv ) { goto test; Func1_1(); Func1_2(); Func1_3(); Func1_4(); Func1_5(); test: CountLines( argc, argv ); return 0; }
/** * @param hFile - file handle. * @param eEncoding - text encoding. * @param dwSignatureSize - size of file signature. */ void CTextView::SetFile(HANDLE hFile, TEXT_ENCODING eEncoding, DWORD dwSignatureSize) { _ASSERTE(hFile != INVALID_HANDLE_VALUE); _ASSERTE(m_hFile == INVALID_HANDLE_VALUE); _ASSERTE(m_hwnd != NULL); m_hFile = hFile; m_pDecoder = CBaseDecoder::GetDecoder(eEncoding); _ASSERTE(m_pDecoder != NULL); SetFilePointer(hFile, dwSignatureSize, NULL, FILE_BEGIN); CountLines(); LoadCache(); ResizeTextView(TRUE); InvalidateRect(m_hwnd, NULL, FALSE); }
bool TextDocument::Insert(GCursor *At, char *Text, int Len) { bool Status = FALSE; if (Text AND Editable) { if (Len < 0) { Len = strlen(Text); } int OldLength = Length; if (SetLength(Length + Len)) { int Offset = (At) ? At->Offset + At->x : 0; // save undo info if (!IgnoreUndo) { TruncateQueue(); // add new undo info in if (UserAction *a = new UserAction) { a->Text = NewStr(Text, Len); a->x = At->x; a->y = At->y; a->Insert = true; Queue.Insert(a); UndoPos = Queue.GetItems(); } } memmove(Data + Offset + Len, Data + Offset, OldLength - Offset + 1); memcpy(Data + Offset, Text, Len); if (At) { At->Length = StrLen(Data + At->Offset); } Lines += CountLines(Text, Len); Status = true; Dirty = true; } } return Status; }
bool TextDocument::Load(char *File) { bool Status = FALSE; if (Open(File, O_READ)) { int FileSize = F.GetSize(); if (SetLength(FileSize)) { F.Read(Data, FileSize); CrLf = FALSE; char *In = Data, *Out = Data; int Size = 0; for (int i=0; i<FileSize; i++, In++) { if (*In != '\r') { *Out++ = *In; Size++; } else { if (In[1] != '\n') { // Macintrash file *Out++ = '\n'; Size++; } else { CrLf = TRUE; } } } Status = SetLength(Size); Data[Length] = 0; Lines = max(CountLines(Data), 1); } F.Close(); Dirty = FALSE; } return Status; }
/***************************************************************************** ReadChannelState() Read the state of the channel from a previous run. Currently just read an ASCII file, with the unique channel IDs in the first column and the amount of storage in the second column (m3) *****************************************************************************/ void ReadChannelState(char *Path, DATE * Now, Channel * Head) { char InFileName[BUFSIZ + 1] = ""; char Str[BUFSIZ + 1] = ""; Channel *Current = NULL; FILE *InFile = NULL; int i = 0; int NLines = 0; int max_seg = 0; RECORDSTRUCT *Match = NULL; RECORDSTRUCT *Record = NULL; /* Re-create the storage file name and open it */ sprintf(Str, "%02d.%02d.%04d.%02d.%02d.%02d", Now->Month, Now->Day, Now->Year, Now->Hour, Now->Min, Now->Sec); sprintf(InFileName, "%sChannel.State.%s", Path, Str); OpenFile(&InFile, InFileName, "r", TRUE); NLines = CountLines(InFile); rewind(InFile); /* Allocate memory and read the file */ Record = (RECORDSTRUCT *) calloc(NLines, sizeof(RECORDSTRUCT)); if (Record == NULL) ReportError("ReadChannelState", 1); for (i = 0; i < NLines; i++) fscanf(InFile, "%hu %f", &(Record[i].id), &(Record[i].storage)); qsort(Record, NLines, sizeof(RECORDSTRUCT), CompareRecord); /* Assign the storages to the correct IDs */ Current = Head; while (Current) { Match = bsearch(&(Current->id), Record, NLines, sizeof(RECORDSTRUCT), CompareRecordID); if (Current->id > max_seg) max_seg = Current->id; if (Match == NULL) ReportError("ReadChannelState", 55); Current->storage = Match->storage; Current = Current->next; } /* Clean up */ if (Record) free(Record); fclose(InFile); }
bool TextDocument::Delete(GCursor *From, int Len, char *Buffer) { bool Status = FALSE; if (From AND Editable) { int Offset = From->Offset + From->x; Len = min(Length - Offset, Len); // -1 is for NULL terminator if (Len > 0) { char *c = Data + Offset; if (!IgnoreUndo) { TruncateQueue(); // add new undo info in if (UserAction *a = new UserAction) { a->Text = NewStr(c, Len); a->x = From->x; a->y = From->y; a->Insert = false; Queue.Insert(a); UndoPos = Queue.GetItems(); } } if (Buffer) { memcpy(Buffer, c, Len); } Lines -= CountLines(c, Len); memmove(c, c + Len, Length - Offset - Len + 1); Status = SetLength(Length - Len); From->Length = StrLen(Data + From->Offset); Dirty = TRUE; } } return Status; }
bool TextDocument::Import(char *s, int Length) { bool Status = FALSE; if (s) { if (Length < 0) { Length = strlen(s); } if (SetLength(Length)) { CrLf = FALSE; char *In = s, *Out = Data; int Size = 0; for (int i=0; i<Length; i++, In++) { if (*In != '\r') { *Out++ = *In; Size++; } else { CrLf = TRUE; } } Status = SetLength(Size + 1); Data[Size] = 0; Lines = max(CountLines(Data), 1); } Dirty = FALSE; } return Status; }
virtual void KeyDown(const char *bytes, int32 numBytes) { int32 mods = 0; BMessage* msg = Window() ? Window()->CurrentMessage() : 0; if( msg ) { msg->FindInt32("modifiers",&mods); } if( *bytes == B_ESCAPE ) { BString tmp = mOrigText; mOrigText = Text(); SetText(tmp.String()); mHasChanged = true; BMessage msg(INLINE_FINALUPDATE_MSG); mOwner.SendMessage(&msg); return; } if( *bytes == '\n' || *bytes == '\r' ) { BMessage msg(INLINE_FINALUPDATE_MSG); mOwner.SendMessage(&msg); return; } if( Window() && Parent() ) { if( *bytes == B_UP_ARROW && CurrentLine() <= 0 ) { BMessage msg(INLINE_GOTOPREVIOUS_MSG); mOwner.SendMessage(&msg); return; } else if( *bytes == B_DOWN_ARROW && CurrentLine() >= (CountLines()-1) ) { BMessage msg(INLINE_GOTONEXT_MSG); mOwner.SendMessage(&msg); return; } } inherited::KeyDown(bytes, numBytes); }
void FormatText::MeasureText(FTTextureFont* font, const char* text, float maxwidth, Vector* sizeOut) { if(maxwidth < 1) { float width = MeasureTextWidth(font, text); float height = FormatText::GetFaceMaxHeight(font);// * 0.75; // Do I really want this scaled? sizeOut->SetXyzw(width, height, 0, 0); return; } else { float outLongestLine = -1; float lines = (float) CountLines(font, text, maxwidth, &outLongestLine); float width = outLongestLine; if(lines == 1) { width = MeasureTextWidth(font, text); } float height = lines * FormatText::GetFaceMaxHeight(font); sizeOut->SetXyzw(width, height, 0, 0); return; } }
void KouhoView::HighlightLine( int32 line ) { //printf( "highlightLine set to :%d\n", line); int32 begin, end; BRegion region; if ( line != -1 ) { begin = OffsetAt( line ); if ( line == CountLines() - 1 ) end = TextLength() + 1; else end = OffsetAt( line + 1 ) - 1; //printf( "Highlight line:%d, offset %d-%d\n", line,begin,end); GetTextRegion( begin, end, ®ion ); //as hightlight is just one line, 0 is enough. highlightRect = region.RectAt( 0 ); //extend highlihght region to right end highlightRect.right = Bounds().right; Invalidate( highlightRect ); } }
void SECEditView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { ASSERT_VALID(this); ASSERT_VALID(pDC); SECEdit* pEdit = GetEdit(); ASSERT(pEdit != NULL); // get the latest page setup values from the registry dlgPageSetup.Initialize(); LPCTSTR pszFileName = GetDocument()->GetPathName(); BOOL bForceSysTime = _tcschr(pszFileName, '.') == NULL; CTime timeSys = CTime::GetCurrentTime(); CFileStatus status; CFile::GetStatus(pszFileName, status); if (dlgPageSetup.m_iHeaderTime != 0 || bForceSysTime) m_timeHeader = timeSys; else m_timeHeader = status.m_mtime; if (dlgPageSetup.m_iFooterTime != 0 || bForceSysTime) m_timeFooter = timeSys; else m_timeFooter = status.m_mtime; if (m_hPrinterFont == NULL) { // get current screen font object metrics CFont* pFont = &m_font; LOGFONT lf; LOGFONT lfSys; if (pFont == NULL) return; VERIFY(pFont->GetObject(sizeof(LOGFONT), &lf)); VERIFY(::GetObject(::GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lfSys)); if (lstrcmpi((LPCTSTR)lf.lfFaceName, (LPCTSTR)lfSys.lfFaceName) == 0) return; // map to printer font metrics HDC hDCFrom = ::GetDC(NULL); lf.lfHeight = ::MulDiv(lf.lfHeight, pDC->GetDeviceCaps(LOGPIXELSY), ::GetDeviceCaps(hDCFrom, LOGPIXELSY)); lf.lfWidth = ::MulDiv(lf.lfWidth, pDC->GetDeviceCaps(LOGPIXELSX), ::GetDeviceCaps(hDCFrom, LOGPIXELSX)); ::ReleaseDC(NULL, hDCFrom); // create it, if it fails we just use the printer's default. m_hMirrorFont = ::CreateFontIndirect(&lf); m_hPrinterFont = m_hMirrorFont; } // select the font so we can calc the metrics CFont* pOldFont = NULL; if (m_hPrinterFont != NULL) pOldFont = pDC->SelectObject(CFont::FromHandle(m_hPrinterFont)); /* Get the height of one line and the height of a page */ // get some constants int iWidth = pDC->GetDeviceCaps(HORZRES); int iHeight = pDC->GetDeviceCaps(VERTRES); // calculate our print rect CRect rect; rect.top = rect.left = 0; rect.bottom = iHeight; rect.right = iWidth; TEXTMETRIC metrics; pDC->GetTextMetrics(&metrics); m_iPrintLineHeight = metrics.tmHeight+metrics.tmExternalLeading; int iPageHeight = pDC->GetDeviceCaps(VERTRES); int iCharWidth = metrics.tmAveCharWidth; int maxchars = rect.Width() / iCharWidth; maxchars--; // go thru global OEPageSetupDlg to format the header and footer CString strHeader; dlgPageSetup.FormatHeader(strHeader, m_timeHeader, pszFileName, 1); CString strFooter; dlgPageSetup.FormatFooter(strFooter, m_timeFooter, pszFileName, 1); // exlude space for the header if (!strHeader.IsEmpty()) iPageHeight -= m_iPrintLineHeight + m_iPrintLineHeight / 4 + m_iPrintLineHeight / 4; // exlude space for the footer if (!strFooter.IsEmpty()) iPageHeight -= m_iPrintLineHeight + m_iPrintLineHeight/4 + m_iPrintLineHeight/4; m_iLinesPerPage = iPageHeight / m_iPrintLineHeight; if (pOldFont != NULL) { ////////////////////////////////////////////////////// // Pagination. Note we have to do it here to be able to // give an accurate page count to the print preview code. // it's not just a count of lines because we wrap lines // that won't fit inside the rect. // PLINEDESC pFirst,pSecond; int iLineCount = 0; SECEdit* pEdit = GetEdit(); ASSERT(pEdit != NULL); if (m_bPrintSelection) { pFirst = m_BlockStart.pLine; pSecond = m_BlockEnd.pLine->pNext; } else { pFirst = pEdit->ListGetFirst(m_pTopLine,NULL); pSecond = NULL; } iLineCount = CountLines(); m_PageList.RemoveAll(); // set the array's initial size to allow for a bunch of split lines m_PageList.SetSize(iLineCount/m_iLinesPerPage+8); int iPage = 0; m_PageList.SetAt(iPage,pEdit->GetLineNo(pFirst)); iLineCount = 0; int iTotalLines = 0; while (pFirst != pSecond) { int iAddLines = 0; if ((pFirst->iTxtSize - pEdit->m_iLineEndLength) > maxchars) { int iSize = pFirst->iTxtSize; // first (maybe) adjust for OE_CR/OE_LF char cFirst,cSecond; cFirst = pFirst->pText[iSize-pEdit->m_iLineEndLength]; cSecond = pEdit->m_szLineEnd[0]; if (cFirst == cSecond) iSize -= pEdit->m_iLineEndLength; iAddLines = iSize / maxchars; if (iSize % maxchars) iAddLines++; iTotalLines += iAddLines; // skip this whole line if it's the last line of a // page, so we don't have to handle a line being // split across pages if ((iLineCount+iAddLines) <= m_iLinesPerPage) { iLineCount += iAddLines; iAddLines = 0; } } else { iLineCount++; iTotalLines++; } if ((iLineCount+iAddLines) >= m_iLinesPerPage) { if (pFirst->pNext) { iPage++; int iLineNo = pEdit->GetLineNo(pFirst); if (!iAddLines) iLineNo++; m_PageList.SetAtGrow(iPage,iLineNo); iLineCount = 0; } } if (!iAddLines) pFirst = pFirst->pNext; } pInfo->SetMaxPage(iPage+1); pDC->SelectObject(pOldFont); } ASSERT_VALID(this); }
INT32 LibraryFile::Init(SuperGallery *ParentGal, PathName *APath, SGLibType Type, BOOL Updated, BOOL DoScroll) { #ifndef EXCLUDE_GALS if(ParentGal == NULL || APath == NULL || !Libraries.IsEmpty()) { ERROR3("LibraryFile::Init - NULL parameters are illegal OR Init called > 1 times"); if(!Libraries.IsEmpty()) return(Libraries.GetCount()); else return 0; } BOOL ok = TRUE; // Tidy up Path a bit String_256 OurPath(APath->GetPath()); LibraryFile::TidyUpSubPath(&OurPath); // Now point Path to the new pathname PathName ModifiedPath(OurPath); PathName *Path = &ModifiedPath; if(!ModifiedPath.IsValid()) { ERROR3("LibraryFile::Init -> Modified library path is invalid"); return 0; } // Remember the pathname and type MyPath = *Path; MyType = Type; ParentGallery = ParentGal; if(ParentGallery->IsKindOf(CC_RUNTIME_CLASS(LibraryGallery))) ParentLibraryGallery = (LibraryGallery *)ParentGal; else { ERROR3("LibraryFile::Init passed a non-library gallery - yikes..."); return 0; } // Need to reset the Quiet status before a stream of Library::Init calls ParentLibraryGallery->SetQuietStatus(FALSE); BOOL Retry = TRUE; while(Retry) { Retry = FALSE; // Would be nice to have a way of adding a file to a path in PathName... Is there one ? if(!SGLibOil::FileExists(Path)) { // We're opening the font gallery, but can't find the font library path - don't warn if(Type == SGLib_Font) return 0; // tell the user that the directory doesn't exist String_256 WarnMsg; String_256 DefaultIndex; String_256 IndexDesc; BOOL CanGenerate; ok = LibraryFile::GetSubIndexDetails(ParentLibraryGallery, &DefaultIndex, &IndexDesc, &CanGenerate); String_256 TmpPath(Path->GetLocation(FALSE)); LibraryFile::TidyUpSubPath(&TmpPath); // Taken out by Graham 30/10/97: If the gallery had no directory specified, //we used to throw a warning which said "do you want to specify another folder?" //We don't do this any more, because the default is to open all galleries empty and //then download stuff from the Xara web site #if 0 WarnMsg.MakeMsg(_R(IDS_BROWSE_OR_SCAN), (TCHAR *)IndexDesc, (TCHAR *)TmpPath); Error::SetError(0, WarnMsg, 0); INT32 ButtonPressed = InformWarning(0, _R(IDS_BROWSE), _R(IDS_RETRY), _R(IDS_CANCEL)/*, _R(IDS_HELP)*/); #else // WEBSTER INT32 ButtonPressed = 3; #endif // WEBSTER TRACEUSER( "Richard", _T("ButtonPressed: %d\n"), ButtonPressed); Error::ClearError(); switch(ButtonPressed) { case 1: { // Open the Browse dialog (or the Add.. dialog as it seems to be called now) PathName ThePath(*Path); // This returns FALSE if Cancel was hit, or an error occurred. if(!SGLibOil::GetLibPath(ParentLibraryGallery, &ThePath, CanGenerate, Type)) { ERROR3("GetLibPath returned FALSE in LF::Init"); return 0; } else { ModifiedPath = ThePath; if(!ModifiedPath.IsValid()) { ERROR3("LibraryFile::Init -> scanned library path is invalid"); return 0; } // Remember the pathname MyPath = ThePath; switch(Type) { case SGLib_ClipArt: case SGLib_Bitmap: LibClipartSGallery::DefaultLibraryPath = MyPath.GetPath(); LibClipartSGallery::ClipartPath = LibClipartSGallery::DefaultLibraryPath; break; case SGLib_ClipArt_WebThemes: LibClipartSGallery::DefaultLibraryPath = MyPath.GetPath(); LibClipartSGallery::WebThemePath = LibClipartSGallery::DefaultLibraryPath; break; #ifndef STANDALONE case SGLib_Texture: case SGLib_Fractal: LibFillsSGallery::DefaultLibraryPath = MyPath.GetPath(); break; case SGLib_Font: // WEBSTER-Martin-09/01/97 - Put back by Ranbir. //#ifndef WEBSTER FontsSGallery::DefaultLibraryPath = MyPath.GetPath(); break; // Not in webster so we get the error below //#endif // WEBSTER #endif default: ERROR2(FALSE,"Library::ScanForLocation Type not present!"); break; } } break; } case 2: Retry = TRUE; #if 0 { // Scan String_256 Result; if(!Library::ScanForLocation(Type, &Result)) { ERROR3("No libraries found..."); return 0; } if(!ModifiedPath.SetPathName(Result)) { ERROR3("LibraryFile::Init -> scanned library path is invalid"); return 0; } // Remember the pathname and type MyPath = *Path; } #endif break; case 3: // Cancel return 0; } } } // Wipe libraries added to gallery for scroll / redraw purposes... InitScrollRedrawSystem(); // Check the actual path exists if(SGLibOil::FileExists(Path)) { // Would be nice to have a way of adding a file to a path in PathName... Is there one ? String_256 IndexFile((const TCHAR *)Path->GetPath(TRUE)); // "%s\\XaraInfo\\index.txt" IndexFile += String_16(_R(IDS_LIBRARIES_XARAINFO_DIRNAME)); IndexFile += TEXT("\\") + String_16(_R(IDS_LIBRARIES_INDEX_FILENAME)); PathName IndexFilePath(IndexFile); if(!IndexFilePath.IsValid()) { ERROR3("LibraryFile::Init indexfilepath is invalid"); return 0; } CCDiskFile MainIndex; if (!MainIndex.InitLexer(FALSE)) { // SetError! ERROR3("LibraryFile::LibraryFile InitLexer failed"); return(0); } if(SGLibOil::FileExists(&IndexFilePath)) { // Count lines in index file INT32 Count = CountLines(&IndexFilePath); TRACEUSER( "Richard", _T("%d lines in index file\n"), Count); // Used for the percentage display INT32 CurrentGroupNumber = 0; // Just in case there's a slow job already going on... SmashSlowJob(); String_64 SlowJob(_R(IDS_LIBRARY_SCANNING)); BeginSlowJob(Count, FALSE, &SlowJob); // Now use the index file to create each group in turn if (MainIndex.open(IndexFilePath, ios::in)) { MainIndex.SetWhitespace(""); // Setting this to blank lets us read non-"'d strings MainIndex.SetDelimiters(","); // ,s delimit our fields MainIndex.SetCommentMarker('#'); // #'d lines are commented out MainIndex.SetStringDelimiters(""); // No string delimiters String_64 Directory; String_64 Description; String_64 SubIndex; String_64 Kind; LexTokenType TT; BOOL EscapePressed = FALSE; while(ok && !EscapePressed) { if(!MainIndex.GetToken()) break; // Get SubLib directory name // Keep reading tokens until we hit a normal one... (skips line ends and // comments for us TT = MainIndex.GetTokenType(); while (TT != TOKEN_NORMAL && ok) { ok = MainIndex.GetToken(); if(!ok) break; TT = MainIndex.GetTokenType(); ok = (TT != TOKEN_EOF); if(!ok) break; } if(!ok) break; Directory = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Directory); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get Description String_256 Description256; Description256 = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Description256); Description256.Left(&Description, 60); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get Sub Library Index name SubIndex = MainIndex.GetTokenBuf(); KillLeadingSpaces(&SubIndex); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get type of files in sublib Kind = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Kind); BOOL Match = FALSE; Match = ParentLibraryGallery->CheckForIndexMatch(&Kind); if(Match) { // Show status of additions EscapePressed = !ContinueSlowJob(CurrentGroupNumber++); // Sort pathname of sublib directory out String_256 SubP(Path->GetPath(TRUE)); SubP += Directory; PathName SubPath(SubP); if(!SubPath.IsValid()) { ERROR3("LibraryFile::Init - invalid subpath"); if(MainIndex.isOpen()) MainIndex.close(); EndSlowJob(); return 0; } // Go ahead and add the new group if(ok) { // Create the sub lib Library *NewSubLib = new Library; if (NewSubLib != NULL) { // Create the new group in the gallery (note the TRUE for create a virtualised one if // we can to save time / memory) if(NewSubLib->Init(ParentGal, &SubPath, &Description, &SubIndex, Type, Updated, TRUE)) { Libraries.AddTail(NewSubLib); // Keep track of libraries added for redraw purposes... AddNewFolderToScrollRedrawSystem(NewSubLib); } else { // This check is new, should be ok... delete NewSubLib; NewSubLib = NULL; ERROR3("Library::Init failed in LibraryFile::Init"); ok = FALSE; } } } } } } else { // Failed to open the index file... // SetError?! ERROR3("LibraryFile::LibraryFile couldn't open index file"); ok = FALSE; } EndSlowJob(); } else { // The directory given had no XaraInfo\index.txt file, maybe it's a sublib, check // For defaults... ok = CheckForSubIndexes(ParentGal, Path, Type, Updated); } // reclaim lexer-buffer memory MainIndex.DeinitLexer(); // And close the file if(MainIndex.isOpen()) MainIndex.close(); // Scroll / redraw the newly added groups... if(DoScroll) DoScrollRedraw(); } else { TRACEUSER( "Richard", _T("Path doesn't exist\n")); } // And return the number of items created return(Libraries.GetCount()); #endif return 0; }
Obj* obj_load(char* path) { ObjData* contVec = CountLines(path); int nVertices = contVec->nVertices; int nCaras = contVec->nCaras; int nNormales = contVec->nNormales; int nTexturas = contVec->nTexturas; //printf("\nParsing %s...",path); Vec3f* listaVertices = (Vec3f*) cg_malloc(sizeof(Vec3f) * nVertices); Vec3i* listaCaras = (Vec3i*) cg_malloc(sizeof(Vec3i) * nCaras); Vec3i* listaNormalCara = (Vec3i*) cg_malloc(sizeof(Vec3i) * nCaras); Vec3i* listaTexturaCara = (Vec3i*) cg_malloc(sizeof(Vec3i)* nCaras); Vec3f* listaNormales = (Vec3f*) cg_malloc(sizeof(Vec3f) * nNormales); Vec2f* listaTexturas = (Vec2f*) cg_malloc(sizeof(Vec2f)* nTexturas); Obj* o = (Obj*) cg_malloc(sizeof(Obj)); o->nVertices = 0; o->nCaras = 0; o->nNormales = 0; o->nTexturas = 0; FILE *file = fopen ( path, "r" ); if( file == NULL ){ printf("File %s error!\n",path); return 0; } char line [ 128 ]; int res = fscanf(file, "%s", line); do { if (strcmp(line,"v")==0) { Vec3f vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z ); listaVertices[o->nVertices] = vertex; //printf("\nVertice %d: ",o->nVertices); //printVector(vertex); o->nVertices++; } else if (strcmp(line,"f")==0) { char c; int vertice1, vertice2, vertice3; int normal1, normal2, normal3; int text1, text2, text3; fscanf(file, "%c %d/%d/%d %d/%d/%d %d/%d/%d\n", &c, &vertice1, &normal1, &text1, &vertice2, &normal2, &text2, &vertice3, &normal3, &text3); //printf("%d/%d/%d %d/%d/%d %d/%d/%d\n", vertice1, normal1, text1, vertice2, normal2, text2, vertice3, normal3, text3); Vec3i f = {vertice1-1,vertice2-1,vertice3-1}; Vec3i n = {normal1-1,normal2-1,normal3-1}; Vec3i t = {text1-1,text2-1,text3-1}; listaCaras[o->nCaras] = f; listaNormalCara[o->nCaras]=n; listaTexturaCara[o->nCaras]=t; o->nCaras++; } else if (strcmp(line,"vn")==0) { Vec3f normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z ); //printf("\nNormal %d: ",o->nNormales); //printVector(normal); listaNormales[o->nNormales] = normal; o->nNormales++; } else if (strcmp(line,"vt")==0) { Vec2f vt; fscanf(file, "%f %f\n", &vt.x, &vt.y ); listaTexturas[o->nTexturas] = vt; o->nTexturas++; } res = fscanf(file, "%s", line); } while (res != EOF); fclose(file); o->listaVertices = listaVertices; o->listaCaras = listaCaras; o->listaNormales = listaNormales; o->listaNormalCara = listaNormalCara; o->listaTexturas = listaTexturas; o->listaTexturaCara = listaTexturaCara; //printf("\nCaras: %d\nVertices: %d\nNormales: %d\nTexturas: %d",o->nCaras,o->nVertices,o->nNormales,o->nTexturas); cg_free(contVec); return o; }
int main(int argc, char* argv[]) { clock_t start, end; start = clock(); // pattern part char *patternFilename = new char[100]; strcpy(patternFilename, "../datafolder/onlydata.txt"); int totalCheckNumberLine = CountLines(patternFilename); int patternLength; // text part char *textFilename = new char[100]; strcpy(textFilename, "../datafolder/longest.txt"); string Text = ReturnString(patternFilename,0); // alphabet part string alphabet = "GTAC "; int alphabetSize = alphabet.length(); //alphabet matrix S Matrix S; std::map<char,Vector> sMap; //result Matrix std::vector<Matrix> SinglePatternResult; for (int j = 0; j <= totalCheckNumberLine ;j++) { if(j == 57054) continue; string Pattern = ReturnString(patternFilename,j).substr(0,32); patternLength = Pattern.length(); S.setsize(patternLength, alphabetSize); S.set(initWithSpecificChar(0.0, patternLength*alphabetSize)); initWithInputString(Pattern,alphabet,S); S=S.transpose(); sMap.clear(); sMap = sMapInit(S,alphabet); SinglePatternResult.clear(); SinglePatternResult.push_back(getExactMatchMatrix(Pattern,Text,sMap)); for (int i = 0;i < errorLimit ;i ++) { SinglePatternResult.push_back(getNextMatrix(Pattern,Text,sMap,SinglePatternResult[i],i)); } Vector outputResult(SinglePatternResult[errorLimit][Pattern.length()-1]); int posnum = 0; int *pos = new int[Text.length()]; for (int i = 0;i < outputResult.getn() ;i ++) { if (outputResult[i] == 1) { cout<<"find it @ position " <<' '<< i+1 << " in "<<j<<" sequence!!!"<<endl; pos[posnum] = i; ++ posnum; } } if(posnum == 0 ) cout<<j<<" sequence!!!"<<endl; delete []pos; } delete []textFilename; delete []patternFilename; end = clock(); // show the clock elipse time std::cout<<"Run time: "<<(double)(end - start) / CLOCKS_PER_SEC<<" s"<<std::endl; return 0; }
HRESULT TextSprite::VOnRestore() { // Two situations: // 1) String should be broken into a multiline entity to fit into a specific area // 2) String sent it need should take up as much space H&V that it needs // Set the width and height CSize sizeText; CSize sizeTotal; std::wstring multiline; if ( m_size.valid() ) { // This is the total to fit into sizeTotal = *m_size; // Fit the original text inside the bounds multiline = g_pApp->GetFontHandler()->ParseMessage( m_text, m_style, sizeTotal); sizeText = g_pApp->GetFontHandler()->GetStringSize(multiline, m_style); } else { // Set the width and height sizeText = g_pApp->GetFontHandler()->GetStringSize(m_text, m_style); sizeTotal = sizeText; multiline = m_text; } int numLines = CountLines(multiline); GCC_ASSERT(sizeTotal.cx > 0 && sizeTotal.cy > 0 && "About to create sprite with no width or height, is this what you want?"); m_TextureWidth = m_Width = sizeTotal.cx; m_TextureHeight = m_Height = sizeTotal.cy; UINT texW = static_cast<UINT>(m_TextureWidth); UINT texH = static_cast<UINT>(m_TextureHeight); UINT numMipLevels = D3DX_DEFAULT; D3DFORMAT format = D3DFMT_UNKNOWN; // This call will reset width, height, and miplevels to the // correct values. if (FAILED (D3DXCheckTextureRequirements( DXUTGetD3D9Device(), &texW, &texH, &numMipLevels, 0, &format, D3DPOOL_DEFAULT ) ) ) { return false; } // Create the texture SAFE_RELEASE(m_pTexture); if ( FAILED ( DXUTGetD3D9Device()->CreateTexture( texW, // width texH, // height numMipLevels, // miplevels - use default 0, // useage - default (not a render target or dynamic) format, // format - unknown format D3DPOOL_DEFAULT, // pool - use default &m_pTexture, // the texture pointer NULL ) ) ) { return false; } m_TextureWidth = texW; m_TextureHeight = texH; // Reinitialize the utility string to count the line breaks std::wstring utilString = multiline; // Size of border CSize sizeBorder( sizeTotal - sizeText ); int initialX = sizeBorder.cx / 2; int initialY = sizeBorder.cy / 2; int deltaY = sizeText.cy / numLines; if (m_isCentered) { // Determine how the lines will be spaced vertically std::wstring firstLine; RemoveFirstLine(utilString, firstLine); CSize const firstLineSize = g_pApp->GetFontHandler()->GetStringSize( firstLine, m_style ); CSize printArea = sizeTotal - sizeBorder; bool const fitsVertically = printArea.cy >= firstLineSize.cy * numLines; if (fitsVertically) { // Enough room, place lines in the center of the print area initialY += (printArea.cy - firstLineSize.cy * numLines) / 2; deltaY = firstLineSize.cy; } else { // Not enough room, squeeze lines on top of each other deltaY = printArea.cy / numLines; initialY += (deltaY - firstLineSize.cy) / 2; } } else { deltaY = g_pApp->GetFontHandler()->GetHeight( m_style ); } //Draw each line one at a time for(int i=0; i<numLines; ++i) { std::wstring line; RemoveFirstLine(multiline, line); int x = initialX; int y = initialY + i * deltaY; if (line.length()) { if ( m_isCentered ) { CSize sizeText = g_pApp->GetFontHandler()->GetStringSize( line, m_style ); x = x + ( sizeTotal.cx - sizeBorder.cx - sizeText.cx ) / 2; } if(FAILED(g_pApp->GetFontHandler()->DrawText( this, line, m_style, CPoint( x, y ) ) ) ) return false; } } return true; }
/** Count the lines on all project's files and display the results. * @param languages Languages definitions * @param nb_languages Number of languages defined in the 'languages' array */ int CodeStatExecDlg::Execute(LanguageDef languages[NB_FILETYPES_MAX], int nb_languages) { cbProject* project = Manager::Get()->GetProjectManager()->GetActiveProject(); long nb_files = project->GetFilesCount(); //wxMessageBox(wxString::Format(_T("Nb files: %ld"), nb_files), _("Error"), wxOK); // Check if all files have been saved bool all_files_saved = true; for (int i=0; i<nb_files; ++i) if (project->GetFile(i)->GetFileState() == fvsModified) all_files_saved = false; // If not, ask user if we can save them if (!all_files_saved) { if (cbMessageBox(_T("Some files are not saved.\nDo you want to save them before running the plugin?"), _("Warning"), wxICON_EXCLAMATION | wxYES_NO, Manager::Get()->GetAppWindow()) == wxID_YES) { for (int i=0; i<nb_files; ++i) { if (project->GetFile(i)->GetFileState() == fvsModified) Manager::Get()->GetEditorManager()->Save(project->GetFile(i)->file.GetFullPath()); } } } // Count code statistics on each file long nb_files_not_found = 0; long nb_skipped_files = 0; long total_lines = 0; long code_lines = 0; long empty_lines = 0; long comment_lines = 0; long codecomments_lines = 0; wxProgressDialog progress(_("Code Statistics plugin"),_("Parsing project files. Please wait...")); for (int i=0; i<nb_files; ++i) { ProjectFile* pf = project->GetFile(i); wxFileName filename(pf->file.GetFullPath(), wxPATH_DOS); if (!filename.FileExists()) { ++nb_files_not_found; //Manager::Get()->GetLogManager()->DebugLog(_T("Code Statistics: Ignoring file '%s' (file not found)"), filename.GetName()); } else { // Find the language associated to the file extension int num_language = -1; for (int l = 0; l<nb_languages; ++l) { for (int j = 0; j<(int)languages[l].ext.Count(); ++j) { if (filename.GetExt() == languages[l].ext[j]) num_language = l; } } // If the language is found, analyse the source file if (num_language > -1) CountLines(filename, languages[num_language], code_lines, codecomments_lines, comment_lines, empty_lines, total_lines); else ++nb_skipped_files; } if (nb_files > 1) progress.Update((100*i)/(nb_files-1)); } progress.Update(100); // Setting-up the statistics dialog box wxXmlResource::Get()->LoadObject(this, parent, _T("dlgCodeStatExec"),_T("wxScrollingDialog")); wxStaticText* txt_num_files = XRCCTRL(*this, "txt_num_files", wxStaticText); txt_num_files->SetLabel(wxString::Format(_("%ld"), nb_files)); wxStaticText* txt_skipped_files = XRCCTRL(*this, "txt_skipped_files", wxStaticText); txt_skipped_files->SetLabel(wxString::Format(_("%ld"), nb_skipped_files)); wxStaticText* txt_files_not_found = XRCCTRL(*this, "txt_files_not_found", wxStaticText); txt_files_not_found->SetLabel(wxString::Format(_("%ld"), nb_files_not_found)); wxStaticText* txt_Code = XRCCTRL(*this, "txt_Code", wxStaticText); txt_Code->SetLabel(wxString::Format(_("%ld"), code_lines)); wxStaticText* txt_Empty = XRCCTRL(*this, "txt_Empty", wxStaticText); txt_Empty->SetLabel(wxString::Format(_("%ld"), empty_lines)); wxStaticText* txt_Comments = XRCCTRL(*this, "txt_Comments", wxStaticText); txt_Comments->SetLabel(wxString::Format(_("%ld"), comment_lines)); wxStaticText* txt_Code_Comments = XRCCTRL(*this, "txt_Code_Comments", wxStaticText); txt_Code_Comments->SetLabel(wxString::Format(_("%ld"), codecomments_lines)); wxStaticText* txt_Total = XRCCTRL(*this, "txt_Total", wxStaticText); txt_Total->SetLabel(wxString::Format(_("%ld"), total_lines)); // If the project is not empty, display the main dialog box if(total_lines) // avoid division by zero on empty document { int icode = static_cast<int>(round(static_cast<double>(100 * code_lines) / static_cast<double>(total_lines))); wxGauge* Gauge_Code = XRCCTRL(*this, "Gauge_Code", wxGauge); Gauge_Code->SetValue(icode); wxStaticText* txt_Gauge_Code = XRCCTRL(*this, "txt_Gauge_Code", wxStaticText); txt_Gauge_Code->SetLabel(wxString::Format(_("%3d%% Code only"), icode)); int icode_comments = static_cast<int>(round(static_cast<double>(100 * codecomments_lines) / static_cast<double>(total_lines))); wxGauge* Gauge_Code_Comments = XRCCTRL(*this, "Gauge_Code_Comments", wxGauge); Gauge_Code_Comments->SetValue(icode_comments); wxStaticText* txt_Gauge_Code_Comments = XRCCTRL(*this, "txt_Gauge_Code_Comments", wxStaticText); txt_Gauge_Code_Comments->SetLabel(wxString::Format(_("%3d%% Code + Comment"), icode_comments)); int icomments = static_cast<int>(round(static_cast<double>(100 * comment_lines) / static_cast<double>(total_lines))); wxGauge* Gauge_Comments = XRCCTRL(*this, "Gauge_Comments", wxGauge); Gauge_Comments->SetValue(icomments); wxStaticText* txt_Gauge_Comments = XRCCTRL(*this, "txt_Gauge_Comments", wxStaticText); txt_Gauge_Comments->SetLabel(wxString::Format(_("%3d%% Comments"), icomments)); int iempty = static_cast<int>(round(static_cast<double>(100 * empty_lines) / static_cast<double>(total_lines))); wxGauge* Gauge_Empty = XRCCTRL(*this, "Gauge_Empty", wxGauge); Gauge_Empty->SetValue(iempty); wxStaticText* txt_Gauge_Empty = XRCCTRL(*this, "txt_Gauge_Empty", wxStaticText); txt_Gauge_Empty->SetLabel(wxString::Format(_("%3d%% Empty"), iempty)); ShowModal(); } else cbMessageBox(_("The project is empty!"), _("Warning"), wxICON_EXCLAMATION | wxOK, Manager::Get()->GetAppWindow()); return 0; }
void FileUtils::qsortfile(string m_fname1,char delimiter) { // TODO: Add your control notification handler code here char line[10240]; Ref* refseq=NULL; if(m_fname1 == "") { cout<<"please input a file for sort!"<<endl; return; } int ret; int total = CountLines(m_fname1); ret = OpenFileForRead(m_fname1); if(!ret) return; ret = OpenFileForWrite(m_fname1); if(!ret) return; ret = AllocBuffer(); if(!ret) return; ret = FirstRead(); if(!ret) { Release(); return; } refseq = new Ref[50000]; if(!refseq) { Release(); return; } cout<<"Begin to process:"<<endl; int k = 0; int count = 0; while(k < total) { ret = GetLine(line,10240); string buffer = line; count = GetFieldsNum(buffer,delimiter); for(int j=0;j<count;j++) { string field = GetField(buffer,j+1,delimiter); strcpy(refseq[k].field[j],field.c_str()); } cout<<"..."; k++; } qsort(refseq,k,sizeof(Ref),cmp); char line1[1024]; line1[0] = '\0'; //write the sorted resuts to file for(int j=0; j<k;j++) { strcpy(line1,""); for(int kk=0;kk<count-1;kk++) { strcat(line1,refseq[j].field[kk]); strcat(line1,"\t"); } strcat(line1,refseq[j].field[count-1]); WriteLine(line1); } LastWrite(); delete[] refseq; Release(); }
void ReadItron(RDArsrc *mainrsrc) { RDArsrc *tmprsrc=NULL; FILE *fp=NULL; char temp[129],custid[16],read_method=0,read_code=0; char new_service=FALSE,tamper[5],readdate[9],read_date[11]; char tim[9],reseq=FALSE; RDATData *prev=NULL; long reading=0; int counters=0,serviceno=0,time_code=0,route=0; int total_time=0; short dec_pos=0,last_type=(-1),hrs=0,mins=0; double new_reading=0.0,seq1=0,new_sequence=0,sequence=0; readwidget(mainrsrc,"FILENAME"); FINDRSCGETSTRING(mainrsrc,"FILENAME",&ITRON_FILENAME); counters=CountLines(ITRON_FILENAME); fp=fopen(ITRON_FILENAME,"r+b"); if(fp==NULL) { prterr("Error Attempting to open and read file [%s] for import.",(ITRON_FILENAME!=NULL ? ITRON_FILENAME:"")); return; } tmprsrc=odiagscrn("DIAGNOSTIC SCREEN",module, "Importing Meter Readings",stop_diagnostic,counters); ZERNRD(utbsvc); if(tmprsrc!=NULL) { if(!APPmakescrn(tmprsrc,TRUE,NULL,NULL,FALSE)) { ForceWindowUpdate(tmprsrc); } else { } } while(fgets(temp,128,fp)) { if(abort_diagnostic) break; if(!strncmp(temp,"RHD",3)) { if(temp[51]=='Y') reseq=TRUE; else reseq=FALSE; } else if(!strncmp(temp,"CUS",3)) { new_service=FALSE; memcpy(custid,&temp[14],15); sprintf(stemp,"%-4s",&temp[30]); serviceno=atoi(stemp); if(temp[98]=='Y') new_service=TRUE; else new_service=FALSE; last_type=0; } else if(!strncmp(temp,"MTR",3)) { sprintf(stemp,"%-8s",&temp[61]); sequence=atoi(stemp); sprintf(stemp,"%-8s",&temp[69]); new_sequence=atoi(stemp); sprintf(stemp,"%-3s",&temp[95]); time_code=atoi(stemp); total_time+=time_code; last_type=1; } else if(!strncmp(temp,"RTR",3)) { sprintf(stemp,"%-6s",&temp[5]); route=atoi(stemp); ZERNRD(utbrte); FINDFLDSETINT(utbrte,"ROUTE NUMBER",route); if(!ADVEQLNRDsec(utbrte,1,SCRNvirtualSubData,mainrsrc)) { prev=RDATDataNEW(utbrte); } else { if(prev!=NULL) FreeRDATData(prev); KEYNRD(utbrte,1); } memset(stemp,0,101); hrs=total_time/60; mins=(total_time-(hrs*60)); sprintf(stemp,"%02d:%02d:00",hrs,mins); FINDFLDSETSTRING(utbrte,"TIME ALLOWED",stemp); ADVWRTTRANSsec(utbrte,0,NULL,prev,SCRNvirtualSubData,mainrsrc); if(prev!=NULL) FreeRDATData(prev); memset(stemp,0,101); } else if(!strncmp(temp,"RDG",3)) { read_method=temp[25]; read_code=temp[61]; memset(stemp,0,101); strncpy(stemp,&temp[33],10); reading=atol(stemp); sprintf(stemp,"%-2s",&temp[91]); dec_pos=atoi(stemp); new_reading=FixReading(reading,dec_pos); memcpy(readdate,&temp[47],8); sprintf(read_date,"%.2s/%.2s/%.4s",&readdate[0],&readdate[2],&readdate[4]); sprintf(tim,"%.2s:%.2s:%.2s",&temp[55],&temp[57],&temp[59]); if(read_code!='S' && read_code!=0) { if(read_method!='R' && read_method!='W') { if(last_type<2) /* Normal Reading */ { /* WRITE UTBSVC NORMAL */ ZERNRD(utbsvc); FINDFLDSETSTRING(utbsvc,"CUSTOMER IDENTIFICATION",custid); FINDFLDSETINT(utbsvc,"SERVICE NUMBER",serviceno); if(!ADVEQLNRDsec(utbsvc,1,SCRNvirtualSubData,mainrsrc)) { prev=RDATDataNEW(utbsvc); FINDFLDGETDOUBLE(utbsvc,"SEQUENCE NUMBER",&seq1); FINDFLDSETDOUBLE(utbsvc,"CURRENT READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(seq1!=new_sequence && reseq==TRUE) { FINDFLDSETCHAR(utbsvc,"RESEQUENCE",TRUE); FINDFLDSETDOUBLE(utbsvc,"NEW SEQUENCE NUMBER",new_sequence); } #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,prev,SCRNvirtualSubData,mainrsrc); if(prev!=NULL) FreeRDATData(prev); } else if(new_service==TRUE) { if(prev!=NULL) FreeRDATData(prev); KEYNRD(utbsvc,1); FINDFLDSETDOUBLE(utbsvc,"CURRENT READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(reseq==TRUE) FINDFLDSETDOUBLE(utbsvc,"SEQUENCE NUMBER",new_sequence); #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,NULL,SCRNvirtualSubData,mainrsrc); } } else { /* Demand Reading */ /* WRITE UTBSVC DEMAND */ ZERNRD(utbsvc); FINDFLDSETSTRING(utbsvc,"CUSTOMER IDENTIFICATION",custid); FINDFLDSETINT(utbsvc,"SERVICE NUMBER",serviceno); if(!ADVEQLNRDsec(utbsvc,1,SCRNvirtualSubData,mainrsrc)) { prev=RDATDataNEW(utbsvc); FINDFLDSETDOUBLE(utbsvc,"DEMAND READING",new_reading); ADVWRTTRANSsec(utbsvc,0,NULL,prev,SCRNvirtualSubData,mainrsrc); if(prev!=NULL) FreeRDATData(prev); } else if(new_service==TRUE) { if(prev!=NULL) FreeRDATData(prev); KEYNRD(utbsvc,1); FINDFLDSETDOUBLE(utbsvc,"DEMAND READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(reseq==TRUE) FINDFLDSETDOUBLE(utbsvc,"SEQUENCE NUMBER",new_sequence); #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,NULL,SCRNvirtualSubData,mainrsrc); } } } } last_type=2; } else if(!strncmp(temp,"WRR",3)) { if(read_code!='S' && read_code!=0) { /* WRITE UTBSVC WAND */ sprintf(tamper,"%.4s",&temp[54]); sprintf(stemp,"%-10s",&temp[72]); reading=atoi(stemp); new_reading=FixReading(reading,dec_pos); memcpy(readdate,&temp[58],8); sprintf(read_date,"%.2s/%.2s/%.4s",&readdate[0],&readdate[2],&readdate[4]); sprintf(tim,"%.2s:%.2s:%.2s",&temp[66],&temp[68],&temp[70]); ZERNRD(utbsvc); FINDFLDSETSTRING(utbsvc,"CUSTOMER IDENTIFICATION",custid); FINDFLDSETINT(utbsvc,"SERVICE NUMBER",serviceno); if(!ADVEQLNRDsec(utbsvc,1,SCRNvirtualSubData,mainrsrc)) { prev=RDATDataNEW(utbsvc); FINDFLDGETDOUBLE(utbsvc,"SEQUENCE NUMBER",&seq1); FINDFLDSETDOUBLE(utbsvc,"CURRENT READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(seq1!=new_sequence && reseq==TRUE) { FINDFLDSETCHAR(utbsvc,"RESEQUENCE",TRUE); FINDFLDSETDOUBLE(utbsvc,"NEW SEQUENCE NUMBER",new_sequence); } #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,prev,SCRNvirtualSubData,mainrsrc); if(prev!=NULL) FreeRDATData(prev); } else if(new_service==TRUE) { if(prev!=NULL) FreeRDATData(prev); KEYNRD(utbsvc,1); FINDFLDSETDOUBLE(utbsvc,"CURRENT READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(reseq==TRUE) FINDFLDSETDOUBLE(utbsvc,"SEQUENCE NUMBER",new_sequence); #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,NULL,SCRNvirtualSubData,mainrsrc); } } } else if(!strncmp(temp,"RFF",3)) { if(read_code!='S' && read_code!=0) { /* WRITE UTBSVC RADIO */ sprintf(tamper,"%.2s",&temp[56]); sprintf(stemp,"%-10s",&temp[72]); reading=atoi(stemp); new_reading=FixReading(reading,dec_pos); memcpy(readdate,&temp[58],8); sprintf(read_date,"%.2s/%.2s/%.4s",&readdate[0],&readdate[2],&readdate[4]); sprintf(tim,"%.2s:%.2s:%.2s",&temp[66],&temp[68],&temp[70]); ZERNRD(utbsvc); FINDFLDSETSTRING(utbsvc,"CUSTOMER IDENTIFICATION",custid); FINDFLDSETINT(utbsvc,"SERVICE NUMBER",serviceno); if(!ADVEQLNRDsec(utbsvc,1,SCRNvirtualSubData,mainrsrc)) { prev=RDATDataNEW(utbsvc); FINDFLDGETDOUBLE(utbsvc,"SEQUENCE NUMBER",&seq1); FINDFLDSETDOUBLE(utbsvc,"CURRENT READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(seq1!=new_sequence && reseq==TRUE) { FINDFLDSETCHAR(utbsvc,"RESEQUENCE",TRUE); FINDFLDSETDOUBLE(utbsvc,"NEW SEQUENCE NUMBER",new_sequence); } #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,prev,SCRNvirtualSubData,mainrsrc); if(prev!=NULL) FreeRDATData(prev); } else if(new_service==TRUE) { if(prev!=NULL) FreeRDATData(prev); KEYNRD(utbsvc,1); FINDFLDSETDOUBLE(utbsvc,"CURRENT READING",new_reading); FINDFLDSETSTRING(utbsvc,"LAST READ DATE",read_date); #ifdef XXXX if(reseq==TRUE) FINDFLDSETDOUBLE(utbsvc,"SEQUENCE NUMBER",new_sequence); #endif /* XXXX */ ADVWRTTRANSsec(utbsvc,0,NULL,NULL,SCRNvirtualSubData,mainrsrc); } } } else { /* Not used for import */ } } if(tmprsrc!=NULL) { killwindow(tmprsrc); free_rsrc(tmprsrc); tmprsrc=NULL; } quitfunc(mainrsrc); }