size_t RenderV1ToFile(ID3_TagImpl& tag, fstream& file) { if (!file) { return 0; } // Heck no, this is stupid. If we do not read in an initial V1(.1) // header then we are constantly appending new V1(.1) headers. Files // can get very big that way if we never overwrite the old ones. // if (ID3_V1_LEN > tag.GetAppendedBytes()) - Daniel Hazelbaker if (ID3_V1_LEN > tag.GetFileSize()) { file.seekp(0, ios::end); } else { // We want to check if there is already an id3v1 tag, so we can write over // it. First, seek to the beginning of any possible id3v1 tag file.seekg(0-ID3_V1_LEN, ios::end); char sID[ID3_V1_LEN_ID]; // Read in the TAG characters file.read(sID, ID3_V1_LEN_ID); // If those three characters are TAG, then there's a preexisting id3v1 tag, // so we should set the file cursor so we can overwrite it with a new tag. if (memcmp(sID, "TAG", ID3_V1_LEN_ID) == 0) { file.seekp(0-ID3_V1_LEN, ios::end); } // Otherwise, set the cursor to the end of the file so we can append on // the new tag. else { file.seekp(0, ios::end); } } ID3_IOStreamWriter out(file); id3::v1::render(out, tag); return ID3_V1_LEN; }
void write(Record r) { if (in_cache(r.user_id)) write_to_cache(r); file.seekp(r.user_id * sizeof(Record)); file.write((char*)&r, sizeof(Record)); if (file.fail()) ROS_ERROR("Failed to write record to file. user_id=%d", r.user_id); }
bool Logger::openLog(fstream &file, const string &name) { file.open(name.c_str(), ios::out | ios::app); if (file.is_open()) { file.seekp(0, ios::end); return true; } return false; }
void ReadAlignChunk::chunkFstreamCat (fstream &chunkOut, ofstream &allOut, bool mutexFlag, pthread_mutex_t &mutexVal){ chunkOut.flush(); chunkOut.seekg(0,ios::beg); if (mutexFlag) pthread_mutex_lock(&mutexVal); allOut << chunkOut.rdbuf(); allOut.clear(); if (mutexFlag) pthread_mutex_unlock(&mutexVal); chunkOut.clear(); chunkOut.seekp(0,ios::beg); //set put pointer at the beginning };
void inputData( fstream &fRef ) { Hardware temp; int number; string name; double price; int stock; cout << "Enter the part number (0 - 99, -1 to end input): "; cin >> number; if(!cin) { cerr << "Wrong Input, Exiting Program..."; exit(1); } while ( number != -1 ) { temp.setPartNumber( number ); cout << "Enter the Hardware name: "; cin.ignore(); getline( cin, name ); temp.setHardwareName( name ); cout << "Enter quantity:"; cin >> stock; if(!cin) { cerr << "Wrong Input, Exiting Program..."; exit(1); } temp.setInStock( stock ); cout << "Enter price:"; cin >> price; if(!cin) { cerr << "Wrong Input, Exiting Program..."; exit(1); } temp.setUnitPrice( price ); fRef.seekp( temp.getPartNumber() * sizeof( Hardware ) ); fRef.write( reinterpret_cast< char * >( &temp ), sizeof( Hardware ) ); cout << "Enter the part number (0 - 99, -1 to end input): "; cin >> number; } }
size_t RenderV1ToFile(ID3_TagImpl& tag, fstream& file) { if (!file) { return 0; } if (ID3_V1_LEN > tag.GetAppendedBytes()) { file.seekp(0, ios::end); } else { // We want to check if there is already an id3v1 tag, so we can write over // it. First, seek to the beginning of any possible id3v1 tag file.seekg(0-ID3_V1_LEN, ios::end); char sID[ID3_V1_LEN_ID]; // Read in the TAG characters file.read(sID, ID3_V1_LEN_ID); // If those three characters are TAG, then there's a preexisting id3v1 tag, // so we should set the file cursor so we can overwrite it with a new tag. if (memcmp(sID, "TAG", ID3_V1_LEN_ID) == 0) { file.seekp(0-ID3_V1_LEN, ios::end); } // Otherwise, set the cursor to the end of the file so we can append on // the new tag. else { file.seekp(0, ios::end); } } ID3_IOStreamWriter out(file); id3::v1::render(out, tag); return ID3_V1_LEN; }
void sft(int off, fstream& primary){ PrimaryIndex p, r; primary.seekg(off); primary.seekp(off); primary.clear(); primary.read(reinterpret_cast<char*>(&r), sizeof(PrimaryIndex)); while(!primary.eof() && r.Byte + 1){ off += sizeof(PrimaryIndex); p = r; primary.seekg(off); primary.read(reinterpret_cast<char*>(&r), sizeof(PrimaryIndex)); primary.seekp(off); if(primary.eof()){ primary.clear(); primary.write(reinterpret_cast<char*>(&p), sizeof(PrimaryIndex)); break; } primary.write(reinterpret_cast<char*>(&p), sizeof(PrimaryIndex)); } primary.clear(); }
void student::del1(char *key) { char buf[100],buf1[100],buf2[100],bufx[100]; fd.close(); fd.open("c.txt",ios::in); fd.seekg(0,ios::beg); while(fd) { fd.getline(buf,100,'\n'); strcpy(buf1,buf); strtok(buf1,"|"); char *ptr=strtok(NULL,"\n"); strcpy(bufx,ptr); if(!strcmp(buf1,"\0")){cout<<"\n\nNo data error";getch();return;} if(strcmp(key,buf1)==0) { strcat(buf,"\n"); int y=strlen(buf); int tel=fd.tellg(); fd.close(); fd.open("c.txt",ios::out|ios::in); fd.seekp(tel,ios::beg); fd.seekp(-(y+1),ios::cur); fd<<"*"; fd.close(); del(bufx); return; } } fd.close(); cout<<"\n\nCouldnt del"; return; }
void PrimaryIndex::add(fstream& primary){ int x = fnd(AccountNumber, primary); if(x < 0){ x = -(x + sizeof(PrimaryIndex)); primary.clear(); primary.seekg(x); PrimaryIndex m(0, -5); primary.read(reinterpret_cast<char*>(&m), sizeof(PrimaryIndex)); primary.clear(); if(m.Byte > -1)sft(x, primary); primary.clear(); primary.seekp(x); primary.write(reinterpret_cast<char*>(this), sizeof(PrimaryIndex)); } }
int main(int argc, char **argv) { if(argc == 1) { cout << "<RibbonLife.exe> <M2 file>\n"; return 1; } if(strstr(argv[1], ".m2")) { m2File.open(argv[1], ios::in | ios::out | ios::binary); if(!m2File) { cout << "File could not be opened!\n"; return 1; } m2File.seekg(0x134); m2File.read(reinterpret_cast<char *>(&nRibbons), sizeof(unsigned int)); if(nRibbons == 0) { cout << "No ribbons exist in the model!\n"; return 1; } m2File.read(reinterpret_cast<char *>(&ofsRibbons), sizeof(unsigned int)); int offset = 0x94; for(int i = 0; i < nRibbons; i++, offset += 0xDC) { m2File.seekg(ofsRibbons + offset); m2File.read(reinterpret_cast<char *>(&life1), sizeof(float)); m2File.read(reinterpret_cast<char *>(&life2), sizeof(float)); cout << "Ribbon #" << i + 1 << ":\n" <<"\nLife1: " << life1 <<"\nLife2: " << life2 << '\n'; float newLife = -1; while(newLife < 0 || newLife > 100) { cout << "\nEnter a new life (0 to 100): "; cin >> newLife; } life1 = life2 = newLife; m2File.seekp(ofsRibbons + offset); m2File.write(reinterpret_cast<const char *>(&life1), sizeof(float)); m2File.write(reinterpret_cast<const char *>(&life2), sizeof(float)); cout << '\n'; } cout << "\n *** Lives both written. Saving file...\n\n"; }
// function to update a tool's information void updateRecord( fstream &fRef ) { Tool temp; int part; string name; int stock; double price; // ask user what part to update cout << "Enter the part number for update: "; cin >> part; // set file position pointer to correct tool fRef.seekg( part * sizeof( Tool ) ); // read tool information fRef.read( reinterpret_cast< char * >( &temp ), sizeof( Tool ) ); // display tool information if partNumber is not -1 if ( temp.getPartNumber() != -1 ) { cout << setw( 7 ) << "Record#" << " " << left << setw( 30 ) << "Tool name" << left << setw( 13 ) << "Quantity" << setw( 10 ) << "Cost" << endl; cout << fixed << showpoint; cout << setw( 7 ) << temp.getPartNumber() << " " << left << setw( 30 ) << temp.getToolName() << left << setw( 13 ) << temp.getInStock() << setprecision( 2 ) << setw( 10 ) << temp.getUnitPrice() << '\n' << "Enter the tool name: "; // ask user for new name cin.ignore(); // ignore the newline on the input stream getline( cin, name ); // set new name temp.setToolName( name ); cout << "Enter quantity and price: "; // ask for price and quantity cin >> stock >> price; temp.setInStock( stock ); // set new quantity temp.setUnitPrice( price ); // get new price // set file position pointer and write information to file fRef.seekp( temp.getPartNumber() * sizeof( Tool ) ); fRef.write( reinterpret_cast< char * > ( &temp ), sizeof( Tool ) ); } // end if
void student::modify() { int pos,choice; string key; cout<<"Enter the key"<<endl; cin>>key; pos=search(key); pos=pos-101; cout<<"Before modify position is\n"<<pos; cout<<"Enter which field to modify"; cout<<"\n\n1.NAME,2.USN,3.BRANCH,4.SEM"; cin>>choice; /*name.erase(); usn.erase(); branch.erase(); sem.erase();*/ switch(choice) { case 1:cout<<"\n\nenter the name"<<endl; cin>>name; break; case 2:cout<<"enter the usn"<<endl; cin>>usn; break; case 3:cout<<"enter the branch"<<endl; cin>>branch; break; case 4:cout<<"enter the semester"<<endl; cin>>sem; break; default:cout<<"Wrong selection,Try again"; } cout<<"In delete the position is"<<pos<<endl; buffer.erase(); buffer=name+'|'+usn+'|'+branch+'|'+sem; buffer.resize(100,'$'); f1.open("data.txt"); f1.seekp(pos,ios::beg); f1<<buffer<<endl; f1.close(); }
/** gets the last id entered if it's an existing file ** returns 0 otherwise. */ int getId(fstream &input) { int i=0; //initialized the number of id to 0 int j; input.seekp(0,ios::end); //sets the pointer to end of the stream file if (input.tellg() != 0) //if the pointer is not 0 we know that the file is not empty { char awesome[3]; input.seekg(-2,ios::end); input.get(awesome,3); i = atoi(awesome); input.seekg(-2,ios::cur); input.getline(awesome,3); j = atoi(awesome); if (j) return j; return i; } else return i; //else the file is empty and id is 0 }
int64_t UDTTransport::secure_recvfile(fstream& ofs, int64_t offset, int64_t size) { const int block = 640000; char* tmp = new char[block]; ofs.seekp(offset); int64_t torecv = size; while (torecv > 0) { int unitsize = int((torecv < block) ? torecv : block); if (secure_recv(tmp, unitsize) < 0) break; ofs.write(tmp, unitsize); torecv -= unitsize; } delete [] tmp; return size - torecv; }
void updateRecord(fstream &fRef) { Tool temp; int part; string name; int stock; double price; cout << "Enter the part number for update: "; cin >> part; fRef.seekg( part * sizeof( Tool )); fRef.read( reinterpret_cast< char * >( &temp ), sizeof( Tool )); if ( temp.getPartNumber() != -1 ) { cout << setw( 7 ) << "Record#" << " " << left << setw( 30 ) << "Tool name" << left << setw( 13 ) << "Quantity" << left << setw( 15 ) << "Cost" << endl; cout << fixed << showpoint; cout << setw( 10 ) << temp.getPartNumber() << " " << left << setw( 30 ) << temp.getToolName() << left << setw( 13 ) << temp.getInStock() << setprecision( 2 ) << setw( 7) << temp.getUnitPrice() << '\n' << "Enter the tool name: "; cin.ignore(); getline( cin, name ); temp.setToolName( name ); cout << "Enter quantity and price: "; cin >> stock >> price; temp.setInStock( stock ); temp.setUnitPrice( price ); fRef.seekp( temp.getPartNumber() * sizeof( Tool ) ); fRef.write( reinterpret_cast< char * > ( &temp ), sizeof( Tool ) ); }
// function that receives input void inputData( fstream &fRef ) { Tool temp; // temporary Tool object // temporary variables used to hold user input int number; string name; double price; int stock; // ask user for and set partNumber cout << "Enter the part number (0 - 99, -1 to end input): "; cin >> number; // set Tool members until -1 is entered while ( number != -1 ) { cout << "Enter the tool name: "; // ask user for tool name cin.ignore(); // ignore the newline on the input stream getline( cin, name ); // store tool name in variable name temp.setToolName( name ); // set tool member name temp.setPartNumber( number ); // set part number // ask user for quantity and price cout << "Enter quantity and price: "; cin >> stock >> price; // store input in temporary variables temp.setInStock( stock ); // set inStock temp.setUnitPrice( price ); // set unitPrice // place file position pointer at next write location fRef.seekp( temp.getPartNumber() * sizeof( Tool ) ); // write data to file fRef.write( reinterpret_cast< char * >( &temp ), sizeof( Tool ) ); // ask user for next part number cout << "Enter the part number (0 - 99, -1 to end input): "; cin >> number; } // end while } // end inputData
void inputData(fstream &file) { int record; string toolName; int quantity; double price; cout<<"Enter record number: -1 to End: "; Tool toolProd; cin>>record; while(record > 0) { cout<<"Enter ToolName: "; cin.ignore(); getline(cin,toolName); //cin>>setw(15)>>toolName; cout<<"Enter Quantity: "; cin>>setw(10)>>quantity; cout<<"Enter price: "; cin>>setw(10)>>price; toolProd.setRec(record); toolProd.setTool(toolName); toolProd.setQuant(quantity); toolProd.setPrice(price); file.seekp((toolProd.getRec()-1) * sizeof(Tool)); file.write(reinterpret_cast<const char *> (& toolProd),sizeof(Tool)); cout<<"Enter record number: -1 to End: "; cin>>record; } menu(file); }
int fnd(int x, fstream& primary, bool b){ primary.seekg(0, primary.end); primary.clear(); int l = 0, h = (primary.tellg()) / sizeof(PrimaryIndex) - 1, cr; PrimaryIndex p; while(l <= h){ cr = (l + h) / 2; primary.seekg(cr * sizeof(PrimaryIndex)); primary.read(reinterpret_cast<char*>(&p), sizeof(PrimaryIndex)); if(p.AccountNumber < x)l = cr + 1; else if(p.AccountNumber > x)h = cr - 1; else if(b){ primary.clear(); int x = p.Byte; p.Byte = -1; primary.seekp(cr * sizeof(PrimaryIndex)); primary.write(reinterpret_cast<char*>(&p), sizeof(PrimaryIndex)); return x; }else return (p.Byte == -1? -(cr + 1) * sizeof(PrimaryIndex): p.Byte); } return -(h + 2) * sizeof(PrimaryIndex); }
// Update an account's balance void updateRecord( fstream &updateFile ) { int account = getAccount( "Enter account to update" ); updateFile.seekg( ( account - 1 ) * sizeof( clientData ) ); clientData client; updateFile.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); if ( client.accountNumber != 0 ) { outputLine( cout, client ); cout << "\nEnter charge (+) or payment (-): "; double transaction; // charge or payment cin >> transaction; // should validate client.balance += transaction; outputLine( cout, client ); updateFile.seekp( ( account-1 ) * sizeof( clientData ) ); updateFile.write( reinterpret_cast<const char *>( &client ), sizeof( clientData ) ); }
void chgRcrd(Inventory &a,fstream& file,long record){ //Display data dspRcrd(a,file,record); //Get new data cout << "Enter new data: " << endl; cout << "Item Description: "; cin.ignore(); cin.getline(a.name,NAME); cout << "Quantity on Hand: "; cin >> a.qty; cout << "Wholesale Cost: "; cin >> a.wholesale; cout << "Retail Cost: "; cin >> a.retail; cout << "Date Added to Inventory: "; cin.ignore(); cin.getline(a.dateAdd,DATE); file.seekp(sizeof(a)*record,ios::beg); file.write(reinterpret_cast<char *>(&a),sizeof(a)); }
void write(record * r, int idx)//raksta failā vārdu idx pozīcija { idx >= count() ? file.seekp(0, ios::end) : file.seekp(idx * sizeof(record)); //ja idx lielās par varad skaitu pozicija lēc uz beigām file.write((char*)r,sizeof(record)); };
void append(fstream& db, Record& r) { db.seekp(0, ios_base::end); db.write(reinterpret_cast<const char*>(&r), sizeof(Record)); }
int64_t DataChn::recvfile(const string& ip, int port, int session, fstream& ofs, int64_t offset, int64_t& size, bool secure) { ChnInfo* c = locate(ip, port); if (NULL == c) return -1; while ((NULL == c->m_pTrans) || c->m_pTrans->isConnected()) { pthread_mutex_lock(&c->m_QueueLock); for (vector<RcvData>::iterator q = c->m_vDataQueue.begin(); q != c->m_vDataQueue.end(); ++ q) { if (session == q->m_iSession) { size = q->m_iSize; ofs.seekp(offset); ofs.write(q->m_pcData, size); delete [] q->m_pcData; c->m_vDataQueue.erase(q); pthread_mutex_unlock(&c->m_QueueLock); return size; } } pthread_mutex_unlock(&c->m_QueueLock); if (pthread_mutex_trylock(&c->m_RcvLock) != 0) { // if another thread is receiving data, wait a little while and check the queue again usleep(10); continue; } bool found = false; pthread_mutex_lock(&c->m_QueueLock); for (vector<RcvData>::iterator q = c->m_vDataQueue.begin(); q != c->m_vDataQueue.end(); ++ q) { if (session == q->m_iSession) { size = q->m_iSize; ofs.seekp(offset); ofs.write(q->m_pcData, size); delete [] q->m_pcData; c->m_vDataQueue.erase(q); found = true; break; } } pthread_mutex_unlock(&c->m_QueueLock); if (found) { pthread_mutex_unlock(&c->m_RcvLock); return size; } if (NULL == c->m_pTrans) { // if this is local recv, just wait for the sender (aka itself) to pass the data pthread_mutex_unlock(&c->m_RcvLock); usleep(10); continue; } RcvData rd; if (c->m_pTrans->recv((char*)&rd.m_iSession, 4) < 0) { pthread_mutex_unlock(&c->m_RcvLock); return -1; } if (c->m_pTrans->recv((char*)&rd.m_iSize, 4) < 0) { pthread_mutex_unlock(&c->m_RcvLock); return -1; } if (!secure) { if (session == rd.m_iSession) { if (c->m_pTrans->recvfile(ofs, offset, rd.m_iSize) < 0) { pthread_mutex_unlock(&c->m_RcvLock); return -1; } } else { rd.m_pcData = new char[rd.m_iSize]; if (c->m_pTrans->recv(rd.m_pcData, rd.m_iSize) < 0) { delete [] rd.m_pcData; pthread_mutex_unlock(&c->m_RcvLock); return -1; } } } else { if (session == rd.m_iSession) { if (c->m_pTrans->recvfileEx(ofs, offset, rd.m_iSize, true) < 0) { pthread_mutex_unlock(&c->m_RcvLock); return -1; } } else { rd.m_pcData = new char[rd.m_iSize + 64]; if (c->m_pTrans->recvEx(rd.m_pcData, rd.m_iSize, true) < 0) { delete [] rd.m_pcData; pthread_mutex_unlock(&c->m_RcvLock); return -1; } } } pthread_mutex_unlock(&c->m_RcvLock); if (session == rd.m_iSession) { size = rd.m_iSize; return size; } pthread_mutex_lock(&c->m_QueueLock); c->m_vDataQueue.push_back(rd); pthread_mutex_unlock(&c->m_QueueLock); } size = 0; return -1; }
void wrtStu(fstream &file ,StudentGrade &stu,int rec){ int size=sizeof(stu); file.seekp(rec*size,ios::beg); file.write(reinterpret_cast<char *>(&stu), size); }
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) { 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(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 itabletwopassfnt (fstream &in, modint pr, int isign, size_t nn) { size_t n1, n2, j, k, m, b, s1, s2; modint w, tmp, tmp2, *p1, *p2; if (nn < 2) return; fstream out (filename (fno), ios::in | ios::out | ios::BIN | ios::trunc); for (n1 = 1, n2 = 0; n1 < nn; n1 <<= 1, n2++); n1 = n2 >> 1; n2 -= n1; n1 = 1 << n1; n2 = 1 << n2; // n2 >= n1 modint *wtable = new modint[n2]; size_t *ptable = new size_t[n2]; if (isign > 0) w = pow (pr, modint::modulus - 1 - (modint::modulus - 1) / nn); else w = pow (pr, (modint::modulus - 1) / nn); // treat the input data as a n1 x n2 matrix // first do n2 transforms of length n1 // by fetching n1 x b blocks in memory b = Maxblocksize / n1; if (b > n1) b = n1; modint *data = new modint[(nn < Maxblocksize ? nn : Maxblocksize)]; // init tables tmp = pow (w, nn / n1); tmp2 = 1; for (k = 0; k < n1; k++) { wtable[k] = tmp2; tmp2 *= tmp; } initscrambletable (ptable, n1); tmp = 1; for (k = 0, s1 = 0; k < n2; k += b, s1 += b) { // read the data from the input file in b x b blocks for (j = 0, p1 = data, s2 = s1; j < n1; j += b, p1 += b) { for (m = 0, p2 = p1; m < b; m++, p2 += n1, s2 += n2) { in.seekg (sizeof (modint) * s2); in.read ((char *) p2, sizeof (modint) * b); } // transpose the b x b block transposesquare (p1, b, n1); } // do b transforms of size n1 for (j = 0, p1 = data; j < b; j++, p1 += n1) itablefnt (p1, wtable, ptable, n1); // then multiply the matrix A_ij by exp(isign * -2 pi i j k / nn) for (j = 0, p1 = data; j < b; j++, p1 += n1) { tmp2 = tmp; for (m = 1; m < n1; m++, tmp2 *= tmp) p1[m] *= tmp2; tmp *= w; } // write the data to the scratch file out.write ((char *) data, sizeof (modint) * b * n1); } // then do n1 transforms of length n2 // by fetching n2 x b blocks in memory b = Maxblocksize / n2; if (b > n1) b = n1; // init table if (n2 != n1) { tmp = pow (w, nn / n2); tmp2 = 1; for (k = 0; k < n2; k++) { wtable[k] = tmp2; tmp2 *= tmp; } initscrambletable (ptable, n2); } for (k = 0, s1 = 0; k < n1; k += b, s1 += b) { // read the data from the input file in b x b blocks for (j = 0, p1 = data, s2 = s1; j < n2; j += b, p1 += b) { for (m = 0, p2 = p1; m < b; m++, p2 += n2, s2 += n1) { out.seekg (sizeof (modint) * s2); out.read ((char *) p2, sizeof (modint) * b); } // transpose the b x b block transposesquare (p1, b, n2); } // do b transforms of size n2 for (j = 0, p1 = data; j < b; j++, p1 += n2) itablefnt (p1, wtable, ptable, n2); // write the data to the original file for (j = 0, p1 = data, s2 = s1; j < n2; j += b, p1 += b) { // transpose the b x b block transposesquare (p1, b, n2); for (m = 0, p2 = p1; m < b; m++, p2 += n2, s2 += n1) { in.seekp (sizeof (modint) * s2); in.write ((char *) p2, sizeof (modint) * b); } } } out.close (); remove (filename (fno)); delete[] ptable; delete[] wtable; delete[] data; }
// 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; }
//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; } }
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; }
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; } }