int CSndBuffer::addBufferFromFile(fstream& ifs, const int& len) { int size = len / m_iMSS; if ((len % m_iMSS) != 0) size ++; // dynamically increase sender buffer while (size + m_iCount >= m_iSize) increase(); Block* s = m_pLastBlock; int total = 0; for (int i = 0; i < size; ++ i) { if (ifs.bad() || ifs.fail() || ifs.eof()) break; int pktlen = len - i * m_iMSS; if (pktlen > m_iMSS) pktlen = m_iMSS; ifs.read(s->m_pcData, pktlen); if ((pktlen = ifs.gcount()) <= 0) break; s->m_iLength = pktlen; s->m_iTTL = -1; s = s->m_pNext; total += pktlen; } CGuard::enterCS(m_BufLock); m_pLastBlock = s; m_iCount += size; CGuard::leaveCS(m_BufLock); return total; }
//********************************************************************* // FUNCTION: ReadWordsFromFile // DESCRIPTION: Read all words from the input text file, validate // each word, the store each unique, valid word in a // WorkList. // INPUT: // Parameters: // WorkLists& list - Repository for all unique words. // std::fstream file - The input file object. // OUTPUT: // Return Val: Total number of valid words read from the file. // Parameters: // WorkLists&list - Updated with all unique words read in. // CALLS TO: // ValidateWord // IsWordInList // InsertWordIntoList // PERFORMANCE: f(n) = n //********************************************************************** int ReadWordsFromFile(WorkLists& list, fstream& file) { int wordCount = 0; // Count of words read from file string word; // Current word being read int index; // Index in the work list for the current letter // read from the file until end of file reached while ( ! file.eof() ) { // get the next word from the file file >> word; // ignore blank lines if ( ! word.empty()) { wordCount++; word = ValidateWord(word); // skip invalid words if (! word.empty()) { index = WORK_LIST_INDEX(word[0]); // add the word to the list only if not already encountered if ( ! IsWordInList(list[index], word)) { list[index] = InsertWordIntoList(list[index], word); } // end if // empty the input buffer to prevent erroneous next read word.clear(); } // if } // if } // end return(wordCount); } // ReadWordsFromFile
void display(){ //pass student s; char rrn[5]; int i; fp.open("student.txt", ios::in); if(!fp){ cout<<"Unable to open \n"; } while(!fp.eof()){ fp.getline(rrn , 4, '|'); fp.getline(s.name , 10, '|'); fp.getline(s.usn , 10, '|'); fp.getline(s.sem , 5, '|'); fp.getline(s.age , 5, '|'); fp.getline(s.branch, 5, '\n'); cout<<rrn<<"\t"<<s.name<<"\t"<<s.usn<<"\t"<<s.sem<<"\t"<<s.age<<"\t"<<s.branch<<"\n"; } fp.close(); }
void listHardwares( fstream &hw ) { Hardware temp; cout << setw( 7 ) << "Record#" << " " << left << setw( 30 ) << "Hardware name" << left << setw( 13 ) << "Quantity" << left << setw( 10 ) << "Cost" << endl; for ( int count = 0; count < 100 && !hw.eof(); count++ ) { hw.seekg( count * sizeof( Hardware ) ); hw.read( reinterpret_cast< char * >( &temp ), sizeof( Hardware ) ); if ( temp.getPartNumber() >= 0 && temp.getPartNumber() < 100 ) { cout << fixed << showpoint; cout << left << setw( 7 ) << temp.getPartNumber() << " " << left << setw( 30 ) << temp.getHardwareName() << left << setw( 13 ) << temp.getInStock() << setprecision( 2 ) << left << setw( 10 ) << temp.getUnitPrice() << '\n'; } } }
int student::search(string key) { int flag=0,pos; f1.open("data.txt",ios::in); while(!f1.eof()) { getline(f1,buffer); unpack(); if(key==usn) { cout<<"Record Found"<<endl; pos=f1.tellp(); cout<<"Buffer is "<<buffer<<endl; f1.close(); return pos; } } cout<<"Record not found"<<endl; f1.close(); }
//(PLIK -> TABLICA) Definicja funkcji wczytującej informacje o studentach z pliku "studenci.dat" do tablicy; tuple<Student *, int> wczytajPlikDoTablicy(string FILE_NAME){ //Otworzenie pliku "studenci.dat" w trybie "wejście/odczyt" studenci.open(FILE_NAME, ios::in); //Sprawdzenie czy plik został otwarty poprawnie if (studenci.good() == true) { int liczbaStruktur = 0; string linia; //Pętla zliczająca liczbę linii - rekordów while (getline(studenci, linia)) { liczbaStruktur++; } //Powrót do początku pliku tekstowego studenci.clear(); studenci.seekg(0, ios::beg); //Utworzenie tablicy o zadanej liczbie struktur typu student Student *tablica = new Student[liczbaStruktur]; //Pętla zapisująca dane z pliku do struktur; int i = 0; while (!studenci.eof()) { studenci >> tablica[i].imie >> tablica[i].nazwisko >> tablica[i].rokStudiow; i++; } //Zamknięcie pliku "studenci.dat" otwartego w trybie "wejście/odczyt" studenci.close(); //Funkcja zwraca dwa wyniki: tablicę z danymi oraz jej wielkość; return make_tuple((Student *)tablica, liczbaStruktur); }
// create formatted text file for printing void createTextFile( fstream &readFromFile ) { // create text file ofstream outPrintFile( "print.txt", ios::out ); // exit program if ofstream cannot create file if ( !outPrintFile ) { cerr << "File could not be created." << endl; exit( 1 ); } // end if outPrintFile << left << setw( 10 ) << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) << "First Name" << right << setw( 10 ) << "Balance" << endl; // set file-position pointer to beginning of readFromFile readFromFile.seekg( 0 ); // read first record from record file ClientData client; readFromFile.read( reinterpret_cast< char * >( &client ), sizeof( ClientData ) ); // copy all records from record file into text file while ( !readFromFile.eof() ) { // write single record to text file if ( client.getAccountNumber() != 0 ) // skip empty records outputLine( outPrintFile, client ); // read next record from record file readFromFile.read( reinterpret_cast< char * >( &client ), sizeof( ClientData ) ); } // end while } // end function createTextFile
void search() { stu t; int r; f.open(fname, ios::in); f.read((char*)&t, sizeof(stu)); cout<<"Enter the roll number to be searched for:"; cin>>r; while(!f.eof()) { if(t.roll==r) { cout<<"Roll no found.\n"; //f.read((char*)t, ios::stu); cout<<"Name"<<t.name; cout<<"Class:"; cout<<"Roll number"<<r; //cout<<"Grade:"<<; //cout<<"Marks:"<<; } } f.close(); }
void loadFile() { char archE[80], archS[80]; int idx = 0; char c; cout << "Archivo a Compilar: "; cin >> archE; strncpy(archS, archE, strlen(archE) - 2); archS[strlen(archE)-2] = '\0'; strcat(archS, "eje"); aFuente.open(archE, ios::in | ios::binary ); aObjeto.open(archS); if( aFuente == NULL ) return; if( aObjeto == NULL ) return; while( !aFuente.eof() ) fileArray[idx++] = aFuente.get(); fileArray[idx] = EOF; int i = 0, j=0; while(fileArray[i]!=EOF) { if (colo == 1) cout << "[" << reng << "] "; linea[j++] = fileArray[i]; colo++; if ( fileArray[i] == 10 || fileArray[i + 1] == EOF) { colo = 1; reng++; linea[j++] = '\0'; cout << linea; linea[0] = '\0'; j = 0; } i++; } cout << endl << endl; }
size_t RenderV2ToFile(const ID3_TagImpl& tag, fstream& file) { ID3D_NOTICE( "RenderV2ToFile: starting" ); if (!file) { ID3D_WARNING( "RenderV2ToFile: error in file" ); return 0; } String tagString; io::StringWriter writer(tagString); id3::v2::render(writer, tag); ID3D_NOTICE( "RenderV2ToFile: rendered v2" ); const char* tagData = tagString.data(); size_t tagSize = tagString.size(); // if the new tag fits perfectly within the old and the old one // actually existed (ie this isn't the first tag this file has had) if ((!tag.GetPrependedBytes() && !ID3_GetDataSize(tag)) || (tagSize == tag.GetPrependedBytes())) { file.seekp(0, ios::beg); file.write(tagData, tagSize); } else { String filename = tag.GetFileName(); String sTmpSuffix = ".XXXXXX"; if (filename.size() + sTmpSuffix.size() > ID3_PATH_LENGTH) { // log this return 0; //ID3_THROW_DESC(ID3E_NoFile, "filename too long"); } char sTempFile[ID3_PATH_LENGTH]; strcpy(sTempFile, filename.c_str()); strcat(sTempFile, sTmpSuffix.c_str()); #if ((defined(__GNUC__) && __GNUC__ >= 3 ) || !defined(HAVE_MKSTEMP)) // This section is for Windows folk && gcc 3.x folk fstream tmpOut; createFile(sTempFile, tmpOut); tmpOut.write(tagData, tagSize); file.seekg(tag.GetPrependedBytes(), ios::beg); char *tmpBuffer[BUFSIZ]; while (!file.eof()) { file.read((char *)tmpBuffer, BUFSIZ); size_t nBytes = file.gcount(); tmpOut.write((char *)tmpBuffer, nBytes); } #else //((defined(__GNUC__) && __GNUC__ >= 3 ) || !defined(HAVE_MKSTEMP)) // else we gotta make a temp file, copy the tag into it, copy the // rest of the old file after the tag, delete the old file, rename // this new file to the old file's name and update the handle int fd = mkstemp(sTempFile); if (fd < 0) { remove(sTempFile); //ID3_THROW_DESC(ID3E_NoFile, "couldn't open temp file"); } ofstream tmpOut(fd); if (!tmpOut) { tmpOut.close(); remove(sTempFile); return 0; // log this //ID3_THROW(ID3E_ReadOnly); } tmpOut.write(tagData, tagSize); file.seekg(tag.GetPrependedBytes(), ios::beg); uchar tmpBuffer[BUFSIZ]; while (file) { file.read(tmpBuffer, BUFSIZ); size_t nBytes = file.gcount(); tmpOut.write(tmpBuffer, nBytes); } close(fd); //closes the file #endif ////((defined(__GNUC__) && __GNUC__ >= 3 ) || !defined(HAVE_MKSTEMP)) tmpOut.close(); file.close(); // the following sets the permissions of the new file // to be the same as the original #if defined(HAVE_SYS_STAT_H) struct stat fileStat; if(stat(filename.c_str(), &fileStat) == 0) { #endif //defined(HAVE_SYS_STAT_H) remove(filename.c_str()); rename(sTempFile, filename.c_str()); #if defined(HAVE_SYS_STAT_H) chmod(filename.c_str(), fileStat.st_mode); } #endif //defined(HAVE_SYS_STAT_H) // file = tmpOut; file.clear();//to clear the eof mark openWritableFile(filename, file); } return tagSize; }
// CHECKED void load(fstream &binFile) { int count = 0; // used to read const int BUFFER_SIZE = 256; static char buffer[256]; //This is a marker so if the file is empty binFile.eof will return true char a; binFile.read(reinterpret_cast<char *>(&a), sizeof(a)); // we don't want the data around the stack to be corrupted while (!binFile.eof()) { BookData tempB; // get length and data for title int titleLength; binFile.read(reinterpret_cast<char *>(&titleLength), sizeof(int)); if (binFile.eof()) { return; } // Read the data for the title into a local buffer binFile.read(buffer, titleLength); // Null terminate the buffer buffer[titleLength] = '\0'; // get the title tempB.setTitle(buffer); // get length and data for the Isbn int isbnLength; binFile.read(reinterpret_cast<char *>(&isbnLength), sizeof(int)); binFile.read(buffer, isbnLength); buffer[isbnLength] = '\0'; tempB.setIsbn(buffer); // get length and data for the author int authorLength; binFile.read(reinterpret_cast<char *>(&authorLength), sizeof(int)); binFile.read(buffer, authorLength); buffer[authorLength] = '\0'; tempB.setAuthor(buffer); // get length and data for the publisher int pubLength; binFile.read(reinterpret_cast<char *>(&pubLength), sizeof(int)); binFile.read(buffer, pubLength); buffer[pubLength] = '\0'; tempB.setPublisher(buffer); // get length and data for the date added int daLength; binFile.read(reinterpret_cast<char *>(&daLength), sizeof(int)); binFile.read(buffer, daLength); buffer[daLength] = '\0'; tempB.setDateAdded(buffer); // get length and data for the quantity int quantIn; binFile.read(reinterpret_cast<char *>(&quantIn), sizeof(quantIn)); tempB.setQuantity(quantIn); // get length and data for the wholesale double wsIn; binFile.read(reinterpret_cast<char *>(&wsIn), sizeof(wsIn)); tempB.setWholesaleCost(wsIn); // get length and data for the retail price double rpIn; binFile.read(reinterpret_cast<char *>(&rpIn), sizeof(rpIn)); tempB.setRetailPrice(rpIn); //use if you need to read from the old file //get m_empty //bool e; //binFile.read(reinterpret_cast<char *>(&e), sizeof(e)); //if (e) //{ // book[index].isEmpty(); //} // end if //else //{ // book[index].insertBook(); //} // end else if (!binFile.eof()) { //BookData tempB; //tempB.setTitle(buffer); //tempB.setIsbn(buffer); //tempB.setAuthor(buffer); //tempB.setPublisher(buffer); //tempB.setDateAdded(buffer); //tempB.setQuantity(quantIn); //tempB.setWholesaleCost(wsIn); //tempB.setRetailPrice(rpIn); // Add the book to the list bookList.push_back(tempB); } count++; cout << count << endl; } // end while it's a do-while inside a while, weird I know } // end function load
// ***** Loader Functions ***** FileGroupID_t FileGroup::ReadJobInfo(string &FileLine, fstream &ReadData) { const vector <string> TheTagWords = InitTagWords(); bool BadObject = false; FileGroupID_t GroupLocation; while (!FoundEndTag(FileLine, TheTagWords[0]) && !ReadData.eof()) { if (!BadObject) { if (FoundStartTag(FileLine, TheTagWords[1])) // FileLocation { GroupLocation = (FileGroupID_t) StrToSize_t(StripTags(FileLine, TheTagWords[1])); } else if (FoundStartTag(FileLine, TheTagWords[2])) // Files { FileLine = ReadNoComments(ReadData); while (!FoundEndTag(FileLine, TheTagWords[2]) && !ReadData.eof()) { vector <string> TempHold = TakeDelimitedList(FileLine, ','); if (TempHold.empty()) { BadObject = true; cerr << "\nProblem in FileGroup object... Here is the line: " << FileLine << endl; } else if (TempHold.size() == 1) { FileType TempFile(RipWhiteSpace(TempHold[0])); if (!TempFile.ValidConfig()) { cerr << "\nProblem in FileGroup object... Invalid FileType object..." << endl; BadObject = true; } else { AddFile(TempFile); } } else { // Filename and filesize FileType TempFile(RipWhiteSpace(TempHold[0]), StrToOff_t(TempHold[1])); if (!TempFile.ValidConfig()) { cerr << "\nProblem in FileGroup object... Invalid FileType object..." << endl; BadObject = true; } else { AddFile(TempFile); } } FileLine = ReadNoComments(ReadData); } } else { BadObject = true; cerr << "\nProblem in FileGroup object... Here is the line: " << FileLine << endl; } } FileLine = ReadNoComments(ReadData); }// end while loop if (GroupLocation != (FileGroupID_t) string::npos && !BadObject) { myIsConfigured = true; } return(GroupLocation); }
void clGeometryReader::ReadPatch(fstream &file, clPatch &patch) const { int EndOfBlock; int AllRead; char line[LINE_SIZE]; char *ptrLine = line; const char *tkn = " ;:"; int countData; int ID = 0; char type = 'B'; dMatrix GX(4, 4); dMatrix GY(4, 4); dMatrix GZ(4, 4); // Read line file.getline(line, LINE_SIZE); EndOfBlock = 0; AllRead = 0; countData = 0; while(!file.eof() && file.good() && !EndOfBlock) { // Check first character in trimmed line switch(*strtrim(line)) { case '#': case '*': // Comment line file.getline(line, LINE_SIZE); break; case '&': case '$': { // Block specifier int blockCommand = GetBlockSpec(line); switch(blockCommand) { case UNKNOWN_SPEC: throw clExceptionTree("clGeometryReader", "ReadPatch", "Unknown block specifier."); break; case PATCH_SPEC: throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected start of block PATCH."); break; case SURFACE_SPEC: throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected start of block SURFACE."); break; case GEOMETRY_SPEC: throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected start of block GEOMETRY."); break; case END_SPEC: EndOfBlock = 1; break; default: throw clExceptionTree("clGeometryReader", "ReadPatch", "Function GetBlockSpec returned unknown value."); break; } break; } case '/': // End of block specifier EndOfBlock = 1; break; default: if(strlen(strtrim(line)) > 0) { // Data line countData++; switch(countData) { // ID Number case 1: ID = str2int(line); AllRead = 0; break; // blendType case 2: if(chrloc('H', line) != -1) { type = 'H'; } else if(chrloc('B', line) != -1) { type = 'B'; } else { throw clExceptionTree("clGeometryReader", "ReadPatch", "Unknown blending type."); } break; // Matrix GX case 3: case 4: case 5: case 6: ptrLine = strtok(line, tkn); GX.SetElement(countData-2, 1, str2double(ptrLine)); ptrLine = strtok(0, tkn); GX.SetElement(countData-2, 2, str2double(ptrLine)); ptrLine = strtok(0, tkn); GX.SetElement(countData-2, 3, str2double(ptrLine)); ptrLine = strtok(0, tkn); GX.SetElement(countData-2, 4, str2double(ptrLine)); break; // Matrix GY case 7: case 8: case 9: case 10: ptrLine = strtok(line, tkn); GY.SetElement(countData-6, 1, str2double(ptrLine)); ptrLine = strtok(0, tkn); GY.SetElement(countData-6, 2, str2double(ptrLine)); ptrLine = strtok(0, tkn); GY.SetElement(countData-6, 3, str2double(ptrLine)); ptrLine = strtok(0, tkn); GY.SetElement(countData-6, 4, str2double(ptrLine)); break; // Matrix GZ case 11: case 12: case 13: case 14: ptrLine = strtok(line, tkn); GZ.SetElement(countData-10, 1, str2double(ptrLine)); ptrLine = strtok(0, tkn); GZ.SetElement(countData-10, 2, str2double(ptrLine)); ptrLine = strtok(0, tkn); GZ.SetElement(countData-10, 3, str2double(ptrLine)); ptrLine = strtok(0, tkn); GZ.SetElement(countData-10, 4, str2double(ptrLine)); if(countData == 14) { AllRead = 1; // Correct for right hand axis system when type is Bezier if(type=='B') { GX.Transpose(); GX.MirrorColumns(); GY.Transpose(); GY.MirrorColumns(); GZ.Transpose(); GZ.MirrorColumns(); } // Now create the patch patch.SetNumberID(ID); patch.SetGX(GX); patch.SetGY(GY); patch.SetGZ(GZ); patch.SetBlendType(type); } break; // Error default: throw clExceptionTree("clGeometryReader", "ReadPatch", "Wrong number of data lines."); break; } } file.getline(line, LINE_SIZE); break; } } if(!EndOfBlock || !AllRead) { throw clExceptionTree("clGeometryReader", "ReadPatch", "Unexpected end while reading block PATCH."); } }
size_t RenderV2ToFile(const ID3_TagImpl& tag, fstream& file) { ID3D_NOTICE( "RenderV2ToFile: starting" ); if (!file) { ID3D_WARNING( "RenderV2ToFile: error in file" ); return 0; } String tagString; io::StringWriter writer(tagString); id3::v2::render(writer, tag); ID3D_NOTICE( "RenderV2ToFile: rendered v2" ); const char* tagData = tagString.data(); size_t tagSize = tagString.size(); // if the new tag fits perfectly within the old and the old one // actually existed (ie this isn't the first tag this file has had) if ((!tag.GetPrependedBytes() && !ID3_GetDataSize(tag)) || (tagSize == tag.GetPrependedBytes())) { file.seekp(0, ios::beg); file.write(tagData, tagSize); } else { String filename = tag.GetFileName(); #if !defined HAVE_MKSTEMP // This section is for Windows folk FILE *tempOut = tmpfile(); if (NULL == tempOut) { // log this return 0; //ID3_THROW(ID3E_ReadOnly); } fwrite(tagData, 1, tagSize, tempOut); file.seekg(tag.GetPrependedBytes(), ios::beg); uchar tmpBuffer[BUFSIZ]; while (!file.eof()) { file.read((char *)tmpBuffer, BUFSIZ); size_t nBytes = file.gcount(); fwrite(tmpBuffer, 1, nBytes, tempOut); } rewind(tempOut); openWritableFile(filename, file); while (!feof(tempOut)) { size_t nBytes = fread((char *)tmpBuffer, 1, BUFSIZ, tempOut); file.write((char *)tmpBuffer, nBytes); } fclose(tempOut); #else // else we gotta make a temp file, copy the tag into it, copy the // rest of the old file after the tag, delete the old file, rename // this new file to the old file's name and update the handle String sTmpSuffix = ".XXXXXX"; if (filename.size() + sTmpSuffix.size() > ID3_PATH_LENGTH) { // log this return 0; //ID3_THROW_DESC(ID3E_NoFile, "filename too long"); } char sTempFile[ID3_PATH_LENGTH]; strcpy(sTempFile, filename.c_str()); strcat(sTempFile, sTmpSuffix.c_str()); int fd = mkstemp(sTempFile); if (fd < 0) { remove(sTempFile); //ID3_THROW_DESC(ID3E_NoFile, "couldn't open temp file"); } ofstream tmpOut(fd); if (!tmpOut) { tmpOut.close(); remove(sTempFile); return 0; // log this //ID3_THROW(ID3E_ReadOnly); } tmpOut.write(tagData, tagSize); file.seekg(tag.GetPrependedBytes(), ios::beg); uchar tmpBuffer[BUFSIZ]; while (file) { file.read(tmpBuffer, BUFSIZ); size_t nBytes = file.gcount(); tmpOut.write(tmpBuffer, nBytes); } tmpOut.close(); file.close(); remove(filename.c_str()); rename(sTempFile, filename.c_str()); openWritableFile(filename, file); #endif } return tagSize; }
void clGeometryReader::ReadSurface(fstream &file, clSurface &surface) const { int EndOfBlock = 0; // Read line char line[LINE_SIZE]; file.getline(line, LINE_SIZE); while(!file.eof() && file.good() && !EndOfBlock) { // Check first character in trimmed line switch(*strtrim(line)) { case '#': case '*': // Comment line file.getline(line, LINE_SIZE); break; case '$': case '&': { // Block specifier int blockCommand = GetBlockSpec(line); switch(blockCommand) { case UNKNOWN_SPEC: throw clExceptionTree("clGeometryReader", "ReadSurface", "Unknown block specifier."); break; case POINT_SPEC: { // Start of point block dMatrix pointsX, pointsY, pointsZ; ReadPoints(file, pointsX, pointsY, pointsZ); surface.CreatePatches(pointsX, pointsY, pointsZ); file.getline(line, LINE_SIZE); break; } case PATCH_SPEC: { // Start of patch block clPatch *patch = new clPatch; ReadPatch(file, *patch); surface.AddPatch(patch); file.getline(line, LINE_SIZE); break; } case SURFACE_SPEC: // Start of surface block throw clExceptionTree("clGeometryReader", "ReadSurface", "Unexpected start of block SURFACE."); break; case GEOMETRY_SPEC: // Start of geometry block throw clExceptionTree("clGeometryReader", "ReadSurface", "Unexpected start of block GEOMETRY."); break; case END_SPEC: // End of geometry block specification EndOfBlock = 1; break; default: throw clExceptionTree("clGeometryReader", "ReadSurface", "Function GetBlockSpec returned unknown value."); break; } break; } case '/': // End of geometry block specification EndOfBlock = 1; break; default: file.getline(line, LINE_SIZE); break; } } }
void clGeometryReader::ReadGeometry(fstream &file, clGeometry &geometry) const { int numberSurfaces = 0; int EndOfBlock = 0; // Read line char line[LINE_SIZE]; file.getline(line, LINE_SIZE); while(!file.eof() && file.good() && !EndOfBlock) { // Check first character in trimmed line switch(*strtrim(line)) { case '#': case '*': // Comment line file.getline(line, LINE_SIZE); break; case '$': case '&': { // Block specifier int blockCommand = GetBlockSpec(line); switch(blockCommand) { case UNKNOWN_SPEC: throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unknown block specifier."); break; case POINT_SPEC: // Start of point block throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unexpected start of block POINT."); break; case PATCH_SPEC: // Start of patch block throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unexpected start of block PATCH."); break; case SURFACE_SPEC: { // Start of surface block clSurface *surface = new clSurface(numberSurfaces++); ReadSurface(file, *surface); geometry.AddSurface(surface); file.getline(line, LINE_SIZE); break; } case GEOMETRY_SPEC: // Start of geometry block throw clExceptionTree("clGeometryReader", "ReadGeometry", "Unexpected start of block GEOMETRY."); break; case END_SPEC: // End of geometry block specification EndOfBlock = 1; break; default: throw clExceptionTree("clGeometryReader", "ReadGeometry", "Function GetBlockSpec returned unknown value."); break; } break; } case '/': // End of geometry block specification EndOfBlock = 1; break; default: file.getline(line, LINE_SIZE); break; } } }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){ int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; Draw Ahmed; switch (message) { case WM_LBUTTONDOWN: if(!isSecond) X1 = LOWORD(lParam), Y1 = HIWORD(lParam) , isSecond = true; else X2 = LOWORD(lParam) , Y2 = HIWORD(lParam) , InvalidateRect(hWnd, NULL, false); break; case WM_COMMAND: wmId = LOWORD(wParam) , wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId){ case IDM_S: ss.open("input.in") , tmp.clear() , tmp = var; while(var.size()) ss << var.front().x1 << " " << var.front().y1 << " " << var.front().x2 << " " << var.front().y2 << " " << var.front().P <<"\n" , var.pop_front(); var = tmp , ss.close(); break; case IDM_O: clr() , OT = true; InvalidateRect(hWnd, NULL, true); // draw only a line on the screen break; case IDM_DDA_LINE: clr() , BDDA = 1; break; case IDM_MP_LINE: clr() , BMP = true; break; case IDM_MP_CIRCULE: clr() , MPC = true; break; case IDM_CIRC_CART: clr() , cartizen = true; break; case IDM_RES: RES = true; isSecond = false; InvalidateRect(hWnd, NULL, true); // draw only a line on the screen break; case IDM_R: clr() , R = true , InvalidateRect(hWnd , 0 , false); break; case IDM_U: clr() , U = true , InvalidateRect(hWnd , 0 , false); break; case IDM_COL: memset(&color,0,sizeof(color)); color.lStructSize=sizeof(CHOOSECOLOR); color.hwndOwner=hWnd; color.lpCustColors=ccref; color.rgbResult=selcolor; color.Flags=CC_RGBINIT; if(ChooseColor(&color)) selcolor=color.rgbResult; isSecond = false; break; case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); Ahmed.ps = ps ; if(OT == true){ ss.open("input.in"); PT tmst; while(!ss.eof()){ ss >> tmst.x1 >> tmst.y1 >> tmst.x2 >> tmst.y2 >> tmst.P; if (tmst.P == 'D') Ahmed.DDA(tmst.x1 , tmst.y1 , tmst.x2 , tmst.y2 , selcolor); if (tmst.P == 'M') Ahmed.MidPoint(tmst.x1 , tmst.y1 , tmst.x2 , tmst.y2 , selcolor); if (tmst.P == 'C') Ahmed.drawCircle(tmst.x1 , tmst.y1 , Ahmed.Distance(tmst.x1 , tmst.y1 , tmst.x2 , tmst.y2), selcolor); if(tmst.P == 'Z') Ahmed.MIDPOINT_CARTISIEAN(tmst.x1, tmst.y1 , Ahmed.Distance(tmst.x1 , tmst.y1 , tmst.x2 , tmst.y2), selcolor); } ss.close(); clr() , BDDA = true , X1 = X2 = Y1 = Y2 = 0; EndPaint(hWnd, &ps); break; } if(U == true){ if(var.size() != 0){ PT t = var.back(); var.pop_back() , var.push_front(t) ; if (t.P == 'D') Ahmed.DDA(t.x1 , t.y1 , t.x2 , t.y2 , RGB(250,250,250)); if (t.P == 'M') Ahmed.MidPoint(t.x1 , t.y1 , t.x2 , t.y2 , RGB(250,250,250)); if (t.P == 'C') Ahmed.drawCircle(t.x1 , t.y1 , Ahmed.Distance(t.x1,t.y1,t.x2,t.y2), RGB(250,250,250)); if(t.P == 'Z') Ahmed.MIDPOINT_CARTISIEAN(t.x1, t.y1 , Ahmed.Distance(t.x1 , t.y1 , t.x2 , t.y2), RGB(250,250,250)); } clr() , BDDA = true , X1 = X2 = Y1 = Y2 = 0; EndPaint(hWnd, &ps); break; } if(R == true){ if(var.size() != 0){ PT t = var.front(); var.pop_front() , var.push_back(t); if (t.P == 'D') Ahmed.DDA(t.x1 , t.y1 , t.x2 , t.y2 , selcolor); if (t.P == 'M') Ahmed.MidPoint(t.x1 , t.y1 , t.x2 , t.y2 , selcolor); if (t.P == 'C') Ahmed.drawCircle(t.x1 , t.y1 , Ahmed.Distance(t.x1 , t.y1 , t.x2 , t.y2), selcolor); if(t.P == 'Z') Ahmed.MIDPOINT_CARTISIEAN(t.x1, t.y1 , Ahmed.Distance(t.x1 , t.y1 , t.x2 , t.y2), selcolor); } clr() , BDDA = true , X1 = X2 = Y1 = Y2 = 0; EndPaint(hWnd, &ps); break; } if(MPC == true) Ahmed.drawCircle(X1 , Y1 , Ahmed.Distance(X1,Y1,X2,Y2), selcolor) , var.push_back(PT(X1,Y1,X2,Y2,'C')); if(BDDA == true) Ahmed.DDA(X1 , Y1 , X2 , Y2 , selcolor) ,var.push_back(PT(X1,Y1,X2,Y2,'D')); if (BMP == true) Ahmed.MidPoint(X1 , Y1 , X2 , Y2 , selcolor) ,var.push_back(PT(X1,Y1,X2,Y2,'M')); if(cartizen == true) Ahmed.MIDPOINT_CARTISIEAN(X1,Y1 , Ahmed.Distance(X1,Y1,X2,Y2) , selcolor) , var.push_back(PT(X1,Y1,X2,Y2,'Z')); EndPaint(hWnd, &ps) , isSecond = false; break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); }
void logSys::readMemFile(fstream& fs, memBox& v){ v.f.clear(); fs.open(MEMBER_FILE, ios::in); Member ins; //----------------------MEMBER DUMP ZONE--------------------------// string MID, MName, MPass, MAdd, MPhone, MRank, MGen, MemUs; char gend; //----------------------BOOKING DUMP ZONE--------------------------// string BCont; //carries the number of bookings made by a member int BNum; string BMID, BFID, BBID; int sDateD, sDateM, sDateY, eDateD, eDateM, eDateY, sTimeH, sTimeM, eTimeH, eTimeM, bStatus; Date sDate, eDate; Time sTime, eTime; string contain; //used to carry integers and needs to be used to convert to the appropriate format using int //----------------------CHAFF DUMP ZONE-----------------------// string chaff; string firstLine; getline(fs, firstLine, '\n'); v.index = stoi(firstLine); cout << firstLine << endl; while(!fs.eof()){ getline(fs, MID, ';'); getline(fs, MName, ';'); getline(fs, MPass, ';'); getline(fs, MAdd, ';'); getline(fs, MPhone, ';'); getline(fs, MRank, ';'); getline(fs, MGen, ';'); gend = *MGen.begin(); getline(fs, MemUs, ';'); getline(fs, BCont, ';'); BNum = stoi(BCont); if(!MID.empty()){ //check if the read function is reading on an empty line. //if it isn't then instantiate another member Member ins(MID, MName, MPass, MAdd, MPhone, MRank, gend, MemUs); } if(BNum > 0){ while(BNum > 0){ getline(fs,BMID,';'); getline(fs,BFID,';'); getline(fs,BBID,';'); getline(fs,contain,';'); sDateD = stoi(contain); getline(fs,contain, ';'); sDateM = stoi(contain); getline(fs, contain,';'); sDateY = stoi(contain); getline(fs,contain,';'); eDateD = stoi(contain); getline(fs,contain, ';'); eDateM = stoi(contain); getline(fs, contain,';'); eDateY = stoi(contain); getline(fs,contain,';'); sTimeH = stoi(contain); getline(fs,contain, ';'); sTimeM = stoi(contain); getline(fs, contain,';'); eTimeH = stoi(contain); getline(fs, contain,';'); eTimeM = stoi(contain); getline(fs,contain,';'); bStatus = stoi(contain); getline(fs, chaff,'\n'); sDate.day = sDateD; sDate.month = sDateM; sDate.year = sDateY; eDate.day = eDateD; eDate.month = eDateM; eDate.year = eDateY; sTime.hour = sTimeH; sTime.minute = sTimeM; eTime.hour = eTimeH; eTime.minute = eTimeM; Booking bIns(BMID, BFID, BBID, sDate, eDate, sTime, eTime, bStatus); ins.bookingHistory.push_back(bIns); BNum--; } } v.f.push_back(ins); } //Marcus - changed delimiter to ; to standardize fs.close(); }
//倒排索引表生成 void indexTable::createIndexTable() { char ch; int line = 0; for (int i = 0; i < dictionaryMaxSize; i++) { for (int j = 0; j < documentMaxSize; j++) { IT.indexArray[i].TF[j] = 0; //给词频矩阵赋初值 } } fin.open("文档集.txt", ios::in); if (!fin) { cout << "打不开文件--文档集\n"; exit(0); } ch = fin.get(); //计算document的数目 while (!fin.eof()) { if (ch == '\n') { IT.documentSize++; } ch = fin.get(); } IT.documentSize++; fin.close(); //cout << IT.documentSize << endl; //cout << TD.dictionarySize << endl; for (int i = 0; i < TD.dictionarySize; i++) { //计算词频TF fin.open("文档集.txt", ios::in); if (!fin) { cout << "打不开文件--文档集.txt!\n"; exit(0); } IT.indexArray[i].termID = TD.termArray[i].termID; // cout << fin.tellg() << endl; // fin.seekg(0, ios::beg); // cout << fin.tellg() << endl; ch = fin.get(); while (!fin.get()) { //若读到的字符为文本结束符,则扫描结束 if (ch == '\n') { //若读到的字符为回车符,则段落数增1,扫描下一个字符 line++; ch = fin.get(); } if (!strcmp(TD.termArray[i].t, getTerm(ch))) { IT.indexArray[i].TF[line]++; //若特征词典中当前获取特征词和此特征词相等,则TF[][]加1 } ch = fin.get(); getType(ch); ch = fin.get(); ch = fin.get(); } line = 0; fin.close(); } fin.close(); for (int i = 0; i < TD.dictionarySize; i++) { IT.indexArray[i].ni = 0; } //cout << TD.dictionarySize << endl; //cout << IT.documentSize << endl; for (int i = 0; i < TD.dictionarySize; i++) { //计算ni,扫描倒排索引表,对于每一个特征词,统计大于0的词频个数 for (int j = 0; j < IT.documentSize; j++) { if (IT.indexArray[i].TF[j]) { IT.indexArray[i].ni++; } } } fout.open("倒排索引表.txt", ios::out); if (!fout) { cout << "打不开文件--倒排索引表.txt\n"; exit(0); } char s[100]; for (int i = 0; i < TD.dictionarySize; i++) { //把特征词id,词频矩阵,ni输出到文件-倒排索引表.txt sprintf(s, "%3d", IT.indexArray[i].termID); fout << s; //fout << IT.indexArray[i].termID << " "; for (int j = 0; j < IT.documentSize; j++) { sprintf(s, "%5d", IT.indexArray[i].TF[j]); fout << s; //fout << IT.indexArray[i].TF[j] << " "; } sprintf(s, "%5d", IT.indexArray[i].ni); fout << s << endl; //fout << IT.indexArray[i].ni << endl; } fout.close(); }
int main() { extern void readParameters(const char*); readParameters("data/params.txt"); double gsfact=1; double tempmass=0; double oldmass=0; char buffer[maxline]; int particle=0; int i = 0; double resbuff[PTASIZE][4*PHIPASIZE]; double ptbuff[PTASIZE]; double phipbuff[PHIPASIZE]; double weightbuff[PHIPASIZE]; double CHbuff[PTASIZE][4*PHIPASIZE]; double workhorsearr[4*PHIPASIZE+1]; double workhorse[4*PHIPASIZE+1]; gsl_fft_real_wavetable * real; gsl_fft_halfcomplex_wavetable * hc; gsl_fft_real_workspace * work; gsl_spline * workspline1=gsl_spline_alloc (gsl_interp_cspline_periodic, 4*PHIPASIZE+1); gsl_interp_accel * workacc1=gsl_interp_accel_alloc (); switch (PHIPASIZE) { case 2: for(i=0;i<1;i++){ phipbuff[1-i] = 0.25*M_PI*(gaus2x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus2x[i]); weightbuff[i] = gaus2w[i]; weightbuff[1-i] = gaus2w[i]; } break; case 4: for(i=0;i<2;i++){ phipbuff[3-i] = 0.25*M_PI*(gaus4x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus4x[i]); weightbuff[i] = gaus4w[i]; weightbuff[3-i] = gaus4w[i]; } break; case 8: for(i=0;i<4;i++){ phipbuff[7-i] = 0.25*M_PI*(gaus8x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus8x[i]); weightbuff[i] = gaus8w[i]; weightbuff[7-i] = gaus8w[i]; } break; case 10: for(i=0;i<5;i++){ phipbuff[9-i] = 0.25*M_PI*(gaus10x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus10x[i]); weightbuff[i] = gaus10w[i]; weightbuff[9-i] = gaus10w[i]; } break; case 12: for(i=0;i<6;i++){ phipbuff[11-i] = 0.25*M_PI*(gaus12x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus12x[i]); weightbuff[i] = gaus12w[i]; weightbuff[11-i] = gaus12w[i]; } break; case 16: for(i=0;i<8;i++){ phipbuff[15-i] = 0.25*M_PI*(gaus16x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus16x[i]); weightbuff[i] = gaus16w[i]; weightbuff[15-i] = gaus16w[i]; } break; case 20: for(i=0;i<10;i++){ phipbuff[19-i] = 0.25*M_PI*(gaus20x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus20x[i]); weightbuff[i] = gaus20w[i]; weightbuff[19-i] = gaus20w[i]; } break; case 48: for(i=0;i<24;i++){ phipbuff[47-i] = 0.25*M_PI*(gaus48x[i] + 1.0); phipbuff[i] = 0.25*M_PI*(1.0 - gaus48x[i]); weightbuff[i] = gaus48w[i]; weightbuff[47-i] = gaus48w[i]; } break; default: printf(" No abscissas for nPhi = %i !\n",PHIPASIZE); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } cout << "phipbuff[0] = " << phipbuff[0] << endl; cout << "phipbuff[PHIPASIZE-1] = " << phipbuff[PHIPASIZE-1] << endl; massfile.open("pasim.dat", ios::in); namesfile.open("pasinames.dat", ios::in); gsfile.open("gslist.dat",ios::in); pttab.open("data/phipspectra.dat", ios::in); ptfile.open("data/ptarr.dat", ios::in); while (!massfile.eof()) { massfile >> tempmass; gsfile >> gsfact; namesfile.getline(buffer,maxline,'\n'); if (method) { // printf("Integrating for %s with mass %f and spin gs=%f\n",buffer,tempmass,gsfact); if (tempmass < 1.0) { for (int k=0;k<PHIPASIZE;k++) { for (int j=0;j<PTASIZE;j++) { pttab >> resbuff[j][k]; workhorsearr[k]=phipbuff[k]; CHbuff[j][k]=resbuff[j][k]; } // pttab << "\n"; } int j=0; // cout << "i = " << particle << endl; switch (particle) { case 0: cout << "Case 0 = " << buffer << endl; v0file.open("data/results/preresopisv0.dat", ios::out); v2file.open("data/results/preresopisv2.dat", ios::out); v4file.open("data/results/preresopisv4.dat", ios::out); break; case 3: cout << "Case 3 = " << buffer << endl; v0file.open("data/results/preresoKsv0.dat", ios::out); v2file.open("data/results/preresoKsv2.dat", ios::out); v4file.open("data/results/preresoKsv4.dat", ios::out); break; case 16: cout << "Case 16 = " << buffer << endl; v0file.open("data/results/preresopsv0.dat", ios::out); v2file.open("data/results/preresopsv2.dat", ios::out); v4file.open("data/results/preresopsv4.dat", ios::out); break; default: v0file.open("/dev/null", ios::out); v2file.open("/dev/null", ios::out); v4file.open("/dev/null", ios::out); } //phip-table for (double pt=0.01;pt<PTMAX;pt+=PTMAX/PTASIZE) { for(int k=0;k<PHIPASIZE;k++) { ptbuff[j]=pt; workhorsearr[4*PHIPASIZE-k-1]=-phipbuff[k]+2*M_PI; resbuff[j][4*PHIPASIZE-k-1]=resbuff[j][k]; } j++; } for (int j=0;j<PTASIZE;j++) for (int k=0;k<PHIPASIZE;k++) { workhorsearr[2*PHIPASIZE-k-1]=M_PI-phipbuff[k]; resbuff[j][2*PHIPASIZE-k-1]=resbuff[j][k]; resbuff[j][2*PHIPASIZE+k]=resbuff[j][4*PHIPASIZE-k-1]; workhorsearr[2*PHIPASIZE+k]=M_PI+phipbuff[k]; } work = gsl_fft_real_workspace_alloc (4*PHIPASIZE); real = gsl_fft_real_wavetable_alloc (4*PHIPASIZE); hc = gsl_fft_halfcomplex_wavetable_alloc (4*PHIPASIZE); for (int j=0;j<PTASIZE;j++) { for (int k=0;k<4*PHIPASIZE;k++) { //workhorse[k]=10*cos(2*(2*M_PI/4/PHIPASIZE*k-M_PI)); //workhorse[k]=10; //workhorsearr[k]=2*M_PI/4/PHIPASIZE*k-M_PI; workhorse[k]=resbuff[j][k]; } workhorsearr[4*PHIPASIZE]=phipbuff[0]+2*M_PI; workhorse[4*PHIPASIZE]=workhorse[0]; gsl_spline_init (workspline1, workhorsearr, workhorse, 4*PHIPASIZE+1); if (j==0) for (int k=0;k<4*PHIPASIZE;k++) { //printf("{%f,%f},",workhorsearr[k],workhorse[k]); //printf("{%f,%f},",workhorsearr[k],gsl_spline_eval(workspline1,workhorsearr[k],workacc1)); } for (int k=0;k<4*PHIPASIZE;k++) { workhorse[k]=gsl_spline_eval(workspline1,2*M_PI/4/PHIPASIZE*k,workacc1); if (j==0) { //printf("%f wh %f\n",2*M_PI/4/PHIPASIZE*k-M_PI,workhorse[k]); //printf("{%f,%f},",2*M_PI/4/PHIPASIZE*k,workhorse[k]); } } //printf("pt %f wh %f\n",ptbuff[j],workhorse[0]); gsl_fft_real_transform (workhorse,1 ,4*PHIPASIZE, real, work); v0file << ptbuff[j] << "\t"; v0file << workhorse[0]/4/PHIPASIZE; v0file << "\n"; v2file << ptbuff[j]<< "\t"; v2file << workhorse[3]/workhorse[0]; v2file << "\n"; v4file << ptbuff[j]<< "\t"; v4file << workhorse[7]/workhorse[0]; v4file << "\n"; } v0file.close(); v2file.close(); v4file.close(); } else { //don't do anything, just repeat last result } oldmass=tempmass; particle++; } else { // printf("testIntegrating for %s with mass %f and spin gs=%f\n",buffer,tempmass,gsfact); if (tempmass < 1.0)
bool End() override { return iofile.eof(); }
//option 7 void UpdateMemberData ( fstream& ioFile, bool& successful ) { //store the position of the stream(later to be used for seekg/p) streamoff position; ioFile.clear(); int count = 0; if(!ioFile.is_open()) { cout << "\nBinary file not yet open.\nReturning to menu." << endl; Pause(); successful = false; } else { string identity; ReadThisLine("Enter enough of the member's name to " "identify him/her: ", identity); //start at beginning ioFile.seekg(0); while(!ioFile.eof()) { //make a temporary position to hold the beginning of the struc streamoff tempPos = ioFile.tellg(); //read the binary file ioFile.read((char *)&member, sizeof(ClubMember)); if(!ioFile.eof()) { if(((string)member.name).find(identity) != string::npos) { //put the beginning of the struc into the position position = tempPos; //print club member cout << "====================\n" << member.name << endl; cout << "Age: " << member.age << " " << "Balance: $" << member.balance << endl; count++; } } } if(count != 1) { cout << "\n=====>Either more than one member, or no members, " "matched your input.\n=====>You need to identify a " "unique club member to update.\n=====>Try again with " "more specific input.\n" << endl; Pause(); successful = false; } if(count == 1) { cout << "\nUpdating data for the above club member." << endl; string choice; do { cout << "Enter n/a/b to update name/age/balance, or " "q to quit updating this member: "; getline(cin,choice); if(choice == "q") { cout << "\nOK, no more updates for this club member " "at this time." << endl; Pause(); successful = true; } if(choice == "n") { string revisedName; ReadThisLine("Enter revised name: ", revisedName); //clear the array memset(member.name,'\0',31); for(unsigned int i = 0 ; i < revisedName.length(); i++) //store the new name into the struc member.name[i] = revisedName[i]; } if(choice == "a") { int newAge; ReadInt("Enter revised age: ", newAge); //store new age in struc member.age = newAge; } if(choice == "b") { double newBalance; ReadDouble("Enter revised balance: ", newBalance); //store new balance in struc member.balance = newBalance; } } while(choice != "q"); } ioFile.clear(); //go to the position ioFile.seekg(position); ioFile.seekp(position); //finally write the info back into the binary file ioFile.write((char *)&member, sizeof(ClubMember)); successful = true; } }
void student::searchdelete(int mode,char key[]) { char pkey[11],buffer[maxlen*2]={0},sname[26],skey[11],number[5]; int offset,r,flag=0; switch(mode) { case 1: case 2: pdx.open(pindex,ios::out|ios::in); while(!pdx.eof()) { pdx>>pkey; pdx>>offset; r=strcmp(pkey,key); if(r==0) { flag = 1; cout<<"\nRecord Found in Primary Index File!\n"; f.open(file,ios::out|ios::in); f.seekg(offset,ios::beg); unpack(); if(mode==1) { f.close(); cout<<"\nName: "<<name; cout<<"\nUSN: "<<usn; cout<<"\nSem: "<<sem; cout<<"\nDept: "<<dept; } else { usn[0] = '*'; f.seekp(offset, ios::beg); pack(1); strcpy(buffer,usn); strcat(buffer,"\t"); sprintf(number,"%d",offset); strcat(buffer,number); pdx.seekp(-(strlen(buffer)),ios::cur); pdx<<buffer<<endl; sdx.open(sindex,ios::out|ios::in); while(!sdx.eof()) { sdx>>sname; sdx>>skey; r=strcmp(skey,pkey); if(r==0) { sname[0] = '*'; strcpy(buffer,sname); strcat(buffer,"\t"); strcat(buffer,usn); sdx.seekp(-(strlen(buffer)),ios::cur); sdx<<buffer<<endl; } } sdx.close(); } break; } } pdx.close(); if(flag==0) cout<<"\nRecord Not found in Primary Index File!\n"; break; case 3: { sdx.open(sindex,ios::out|ios::in ); while (!sdx.eof()) { sdx>>sname; sdx>>skey; r=strcmp(key,sname); if(r==0) { flag = 1; cout<<"\nRecord Found in Secondary Index file! "; searchdelete(1,skey); break; } } if(flag == 0) cout<<"\nRecord Not found in the Secondary Index file \n"; break; } }
// Thread than listens to the clients and inserts/updates/seraches for them in the file DWORD WINAPI readClient(LPVOID lpParam) { char recvbuf[DEFAULT_BUFFER_LENGTH]; char firstName[DEFAULT_BUFFER_LENGTH]; char lastName[DEFAULT_BUFFER_LENGTH]; char dateOfBirth[DEFAULT_BUFFER_LENGTH]; int iResult; bool exit = false; SOCKET ClientSocket = (SOCKET)lpParam; // Receive until the peer shuts down the connection do { // sending menu to the client memset(recvbuf, 0, sizeof(recvbuf)); strcpy(recvbuf, "Menu:\n1. Insert\n2. Update\n3. Find\n4. Insert more than one\n0. Exit"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); // getting user's choice from the menu memset(recvbuf, 0, sizeof(recvbuf)); recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); // ignore ignore message if (strcmp(recvbuf, "!ignore") == 0) { continue; } // inserting one or more record in the file if (strcmp(recvbuf, "4") == 0) { bool exit = false; bool earlyExit = false; bool fName = true; bool lName = true; int i = 0; int len = strlen(recvbuf); int fNameLen = 0; int lNameLen = 0; memset(firstName, 0, sizeof(firstName)); memset(lastName, 0, sizeof(lastName)); memset(dateOfBirth, 0, sizeof(dateOfBirth)); WaitForSingleObject(streamMutex, INFINITE); stream.open("DataBase.txt", ios::in | ios::out | ios::app); while (exit == false) { memset(recvbuf, 0, sizeof(recvbuf)); WaitForSingleObject(idMutex, INFINITE); // checking if there are room to input at least one record if (id >= 40000) { // if not, send an error message ReleaseMutex(idMutex); strcpy(recvbuf, "\tReached max amount of elements"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); recv(ClientSocket, recvbuf, strlen(recvbuf), 0); earlyExit = true; break; } else { // if yes, send confirmation message ReleaseMutex(idMutex); send(ClientSocket, "OK", strlen("OK"), 0); } // getting one record at a time and checking, if all record were inserted recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); if (strcmp(recvbuf, "!end") == 0) { exit = true; break; } fName = true; lName = true; i = 0; len = strlen(recvbuf); fNameLen = 0; lNameLen = 0; // parsing the input to get first name, last name and the date for (int counter = 0; counter < len; counter++) { if (fName == true) { if (recvbuf[counter] != '\n') { firstName[counter] = recvbuf[counter]; } else { fName = false; firstName[counter] = '\0'; fNameLen = strlen(firstName); } } else if (lName == true) { i = counter - fNameLen - 1; if (recvbuf[counter] != '\n') { lastName[i] = recvbuf[counter]; } else { lName = false; lastName[i] = '\0'; lNameLen = strlen(lastName); } } else { i = counter - fNameLen - lNameLen - 2; dateOfBirth[i] = recvbuf[counter]; } } WaitForSingleObject(idMutex, INFINITE); id++; ReleaseMutex(idMutex); // insert to the file stream << id << "\n"; stream << firstName << "\n"; stream << lastName << "\n"; stream << dateOfBirth << "\n"; } stream.close(); ReleaseMutex(streamMutex); // if all records were added, send confirmation message if (earlyExit == false) { send(ClientSocket, "\tAdded all elements!", strlen("\tAdded all elements!"), 0); recv(ClientSocket, recvbuf, strlen(recvbuf), 0); } continue; } // let client to exit if (strcmp(recvbuf, "0") == 0) { printf("%d is leaving\n", (int)ClientSocket); exit = true; break; } // inserting one record to the file else if (strcmp(recvbuf, "1") == 0) { memset(recvbuf, 0, sizeof(recvbuf)); memset(firstName, 0, sizeof(firstName)); memset(lastName, 0, sizeof(lastName)); memset(dateOfBirth, 0, sizeof(dateOfBirth)); WaitForSingleObject(idMutex, INFINITE); // checking if there are room to input at least one record if (id >= 40000) { strcpy(recvbuf, "Reached max amount of elements"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); ReleaseMutex(idMutex); continue; } else { send(ClientSocket, "OK", strlen("OK"), 0); ReleaseMutex(idMutex); } recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); bool fName = true; bool lName = true; int i = 0; // parsing the input to get first name, last name and the date for (int counter = 0; counter < (int)strlen(recvbuf); counter++) { if (fName == true) { if (recvbuf[counter] != '\n') { firstName[counter] = recvbuf[counter]; } else { fName = false; firstName[counter] = '\0'; } } else if (lName == true) { i = counter - strlen(firstName) - 1; if (recvbuf[counter] != '\n') { lastName[i] = recvbuf[counter]; } else { lName = false; lastName[i] = '\0'; } } else { i = counter - strlen(firstName) - strlen(lastName) - 2; dateOfBirth[i] = recvbuf[counter]; } } WaitForSingleObject(idMutex, INFINITE); id++; ReleaseMutex(idMutex); WaitForSingleObject(streamMutex, INFINITE); // opening the file and inserting the data to it stream.open("DataBase.txt", ios::in | ios::out | ios::app); stream << id << "\n"; stream << firstName << "\n"; stream << lastName << "\n"; stream << dateOfBirth << "\n"; stream.close(); ReleaseMutex(streamMutex); // sending confirmation message and waiting for response send(ClientSocket, "\tAdded!", strlen("\tAdded!"), 0); recv(ClientSocket, recvbuf, strlen(recvbuf), 0); } // updating the record in the file else if (strcmp(recvbuf, "2") == 0) { string nFirstName; string nLastName; string nDateOfBirth; string search; // getting input for updating memset(recvbuf, 0, sizeof(recvbuf)); strcpy(recvbuf, "Enter ID to find"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); memset(recvbuf, 0, sizeof(recvbuf)); recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); search = recvbuf; memset(recvbuf, 0, sizeof(recvbuf)); strcpy(recvbuf, "Enter new first name to update (5 characters max)"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); memset(recvbuf, 0, sizeof(recvbuf)); recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); nFirstName = recvbuf; memset(recvbuf, 0, sizeof(recvbuf)); strcpy(recvbuf, "Enter new last name to update (5 characters max)"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); memset(recvbuf, 0, sizeof(recvbuf)); recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); nLastName = recvbuf; memset(recvbuf, 0, sizeof(recvbuf)); strcpy(recvbuf, "Enter new date of birth to update in the formmat yyyy-mm-dd"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); memset(recvbuf, 0, sizeof(recvbuf)); recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); nDateOfBirth = recvbuf; // opening the file WaitForSingleObject(streamMutex, INFINITE); stream.open("DataBase.txt", ios::in | ios::out); stream.clear(); stream.seekg(0, ios::beg); string line; string firstName; string lastName; string dateOfBirth; bool fail = false; int count = 0; // searching for the ID to change while (1) { if (stream.eof()) { fail = true; break; } getline(stream, line); count += line.length() + 2; if (line == search) { // changing the record stream.seekp(count); stream << nFirstName << endl; stream << nLastName << endl; stream << nDateOfBirth; break; } } // send a message if can not find the ID if (fail == true) { strcpy(recvbuf, "\n\tCan not find the ID\n"); } else { strcpy(recvbuf, "\n\tChanged!\n"); } // closing the file stream.close(); ReleaseMutex(streamMutex); send(ClientSocket, recvbuf, strlen(recvbuf), 0); recv(ClientSocket, recvbuf, strlen(recvbuf), 0); } // finding and diplaying the recond in the file else if (strcmp(recvbuf, "3") == 0) { // getting ID to search memset(recvbuf, 0, sizeof(recvbuf)); strcpy(recvbuf, "Enter ID to search"); send(ClientSocket, recvbuf, strlen(recvbuf), 0); memset(recvbuf, 0, sizeof(recvbuf)); recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0); // opening the file WaitForSingleObject(streamMutex, INFINITE); stream.open("DataBase.txt", ios::in | ios::out | ios::app); stream.clear(); stream.seekg(0, ios::beg); string line; string search = recvbuf; string firstName; string lastName; string dateOfBirth; bool fail = false; // loop to find the information while (1) { if (stream.eof()) { fail = true; break; } getline(stream, line); // reading searched data if (line == search) { getline(stream, firstName); getline(stream, lastName); getline(stream, dateOfBirth); break; } } // sending error message if needed if (fail == true) { strcpy(recvbuf, "\n\tCan not find the ID\n"); } else { // sending data to the client strcpy(recvbuf, "\n"); strcat(recvbuf, "\tFirst Name :"); strcat(recvbuf, firstName.c_str()); strcat(recvbuf, "\n\tLast Name :"); strcat(recvbuf, lastName.c_str()); strcat(recvbuf, "\n\tDate of Birth :"); strcat(recvbuf, dateOfBirth.c_str()); strcat(recvbuf, "\n"); } // closing the file stream.close(); ReleaseMutex(streamMutex); // sending confirmation message and getting message that client got it send(ClientSocket, recvbuf, strlen(recvbuf), 0); recv(ClientSocket, recvbuf, strlen(recvbuf), 0); } // sending error message for invalid input else { send(ClientSocket, "Invalid option", strlen("Invalid option"), 0); } } while (exit == false); // shutdown the send half of the connection since no more data will be sent iResult = shutdown(ClientSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed: %d\n", WSAGetLastError()); } // cleanup WaitForSingleObject(vecMutex, INFINITE); for (vector<SOCKET>::iterator iter = vec.begin(); iter < vec.end(); iter++) { if ((*iter) == ClientSocket) { vec.erase(iter); printf("Deleted the %d from the list\n", ClientSocket); break; } } ReleaseMutex(vecMutex); closesocket(ClientSocket); printf("Closed connection to the %d\n", ClientSocket); return 0; }
void clGeometryReader::ReadPoints(fstream &file, dMatrix &pointsX, dMatrix &pointsY, dMatrix &pointsZ) const { int EndOfBlock; int AllRead; char line[LINE_SIZE]; char *ptrLine = line; const char *tkn = " ;:"; int countData; int rmax = 0; int cmax = 0; // Read line file.getline(line, LINE_SIZE); EndOfBlock = 0; AllRead = 0; countData = 0; while(!file.eof() && file.good() && !EndOfBlock) { // Check first character in trimmed line switch(*strtrim(line)) { case '#': case '*': // Comment line, read next line file.getline(line, LINE_SIZE); break; case '&': case '$': { // Block specifier int blockCommand = GetBlockSpec(line); switch(blockCommand) { case UNKNOWN_SPEC: throw clExceptionTree("clGeometryReader", "ReadPoints", "Unknown block specifier."); break; case POINT_SPEC: throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block POINT."); break; case PATCH_SPEC: throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block PATCH."); break; case SURFACE_SPEC: throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block SURFACE."); break; case GEOMETRY_SPEC: throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected start of block GEOMETRY."); break; case END_SPEC: EndOfBlock = 1; break; default: throw clExceptionTree("clGeometryReader", "ReadPoints", "Function GetBlockSpec returned unknown value."); break; } break; } case '/': // End of block specifier EndOfBlock = 1; break; default: if(strlen(strtrim(line)) > 0) { // Data line countData++; // Matrix specifiers if(countData==1) { // column defines constant u-values ptrLine = strtok(line, tkn); cmax = str2int(ptrLine); // row defines constant v-values ptrLine = strtok(NULL, tkn); rmax = str2int(ptrLine); // Set matrix dimensions pointsX.SetNumberRows(rmax); pointsX.SetNumberColumns(cmax); pointsY.SetNumberRows(rmax); pointsY.SetNumberColumns(cmax); pointsZ.SetNumberRows(rmax); pointsZ.SetNumberColumns(cmax); } // Specification of the x-coordinates else if(countData>=2 && countData<(2+rmax)) { int row = (countData-1); // Set first u-element in current v ptrLine = strtok(line, tkn); pointsX.SetElement(row, 1, str2double(ptrLine)); // Set following u-elements in current v for(int c=2; c<=cmax; c++) { ptrLine = strtok(0, tkn); pointsX.SetElement(row, c, str2double(ptrLine)); } } // Specification of the y-coordinates else if(countData>=(2+rmax) && countData<(2+rmax+rmax)) { int row = (countData-1-rmax); // Set first u-element in current v ptrLine = strtok(line, tkn); pointsY.SetElement(row, 1, str2double(ptrLine)); // Set following u-elements in current v for(int c=2; c<=cmax; c++) { ptrLine = strtok(0, tkn); pointsY.SetElement(row, c, str2double(ptrLine)); } } // Specification of the z-coordinates else if(countData>=(2+rmax+rmax) && countData<(2+rmax+rmax+rmax)) { int row = (countData-1-rmax-rmax); // Set first u-element in current v ptrLine = strtok(line, tkn); pointsZ.SetElement(row, 1, str2double(ptrLine)); // Set following u-elements in current v for(int c=2; c<=cmax; c++) { ptrLine = strtok(0, tkn); pointsZ.SetElement(row, c, str2double(ptrLine)); } } // Too much data else { throw clExceptionTree("clGeometryReader", "ReadPoints", "Too much data."); } if(countData==(1+rmax+rmax+rmax)) { AllRead = 1; } } file.getline(line, LINE_SIZE); break; } } if(!EndOfBlock || !AllRead) { throw clExceptionTree("clGeometryReader", "ReadPoints", "Unexpected end while reading block POINT."); } }
void CAFEDomain::GetConfigInfo(string &FileLine, fstream &ReadData) { const vector<string> TagWords = InitTagWords(); bool BadObject = false; while (!FoundEndTag(FileLine, TagWords[0]) && !ReadData.eof()) { if (!BadObject) { if (FoundStartTag(FileLine, TagWords[1])) // Longitudes { vector <string> Tempy = TakeDelimitedList(StripTags(FileLine, TagWords[1]), ','); if (Tempy.size() == 2) { myDomainLons = StrToFloat(Tempy); if (isnan(myDomainLons[0]) || isnan(myDomainLons[1])) { BadObject = true; cerr << "ERROR -- Invalid values for coordinates. Must be numbers..." << endl; cerr << "The line: " << FileLine << endl; } } else { BadObject = true; cerr << "ERROR -- Incorrect number of coordinates: " << Tempy.size() << endl; cerr << " The Line: " << FileLine << endl; } } else if (FoundStartTag(FileLine, TagWords[2])) //latitudes { vector <string> Tempy = TakeDelimitedList(StripTags(FileLine, TagWords[2]), ','); if (Tempy.size() == 2) { myDomainLats = StrToFloat(Tempy); if (isnan(myDomainLats[0]) || isnan(myDomainLats[1])) { BadObject = true; cerr << "ERROR -- Invalid values for coordinates. Must be numbers..." << endl; cerr << "The line: " << FileLine << endl; } } else { BadObject = true; cerr << "ERROR -- Incorrect number of coordinates: " << Tempy.size() << endl; cerr << "The Line: " << FileLine << endl; } } else { BadObject = true; cerr << "ERROR -- Problem in parent Domain... couldn't recognize anything.\nHere is the line: " << FileLine << endl; } }// end if !BadObject FileLine = ReadNoComments(ReadData); }// end while loop if (myDomainLats.size() == 2 && myDomainLons.size() == 2 && !ReadData.eof() && !BadObject) { myIsConfigured = true; } }// end GetConfigInfo()
void main() { student stud; int n; char namex[25]; clrscr(); cout<<"Enter the number of students in the class:"; cin>>n; ofstream fout("student.dat", ios::binary); for(int i=1;i<=n;i++) { stud.accept(); fout.write((char*)&stud, sizeof(stud)); } fout.close(); ifstream fin("student.dat", ios::binary); while(!fin.eof()) { fin.read((char*)&stud, sizeof(stud)); stud.display(); getche(); } fin.close(); clrscr(); cout<<"Append to file:\n\n"; cout<<""; cout<<"How many new records do you wish to add to the existing file:"; cin>>n; fout.open("student.dat", ios::binary | ios::app); for(i=1;i<=n;i++) { stud.accept(); fout.write((char*)&stud, sizeof(stud)); } fout.close(); fin.open("student.dat", ios::binary); while(!fin.eof()) { fin.read((char*)&stud, sizeof(stud)); stud.display(); getche(); } fin.close(); clrscr(); cout<<"Enter the name of the student whose record you wish to modify:"; cin>>namex; usefile.open("student.dat", ios::binary | ios::in | ios::out); while(!usefile.eof()) { usefile.read((char*)&stud, sizeof(stud)); check(stud, namex); } usefile.close(); cout<<"Sorry Record does not exist"; fin.open("student.dat", ios::binary); while(!fin.eof()) { fin.read((char*)&stud, sizeof(stud)); stud.display(); getche(); } }