TEST(TestCommand, testShownamespacesCommand) { cout << "testShownamespacesCommand" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* writer = new CommandWriter(fos); ShownamespacesCommand cmd; cmd.setDB("testdb"); writer->writeCommand(&cmd); fos->close(); delete fos; delete writer; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); Command* resCmd = reader->readCommand(); EXPECT_TRUE(resCmd->commandType() == SHOWNAMESPACES); ShownamespacesCommand* sw = (ShownamespacesCommand*)resCmd; EXPECT_TRUE(sw->DB()->compare("testdb") == 0); fis->close(); delete resCmd; delete fis; delete reader; }
void MergeStreams(FileInputStream * in1, FileInputStream * in2, char * outfile) { FileOutputStream * outStream = NULL; try { int nbytes; char buffer[1]; outStream = new FileOutputStream(outfile); while ((nbytes = (in1->read(buffer, 1)) != -1)) { outStream->write(buffer, nbytes); } while ((nbytes = (in2->read(buffer, 1)) != -1)) { outStream->write(buffer, nbytes); } delete outStream; } catch (IOException & err) { err.Display(); cout<<"Deleting dynamic outStream object"<<endl; delete outStream; throw FileNotFoundException(outfile); } catch (Xception & err) { err.Display(); cout<<"Deleting dynamic FileOutputStream object"<<endl; delete outStream; throw FileNotFoundException(outfile); } }
const String LumaPlug::LumaDocument::saveDocument (const File& file) { if (file.exists()) { bool deleteSuccess = file.deleteFile(); if (!deleteSuccess) { return String("Delete of existing file failed!"); } } FileOutputStream* stream = file.createOutputStream(); if (!stream) { return String("Failed to obtain output stream to save file!"); } String scriptText = plug->getScriptText(); if (scriptText.length() > 0) { bool writeSuccess = stream->write(scriptText.toUTF8(), scriptText.length()); if (!writeSuccess) { return String("Write to output stream failed!"); } stream->flush(); } return String::empty; }
TEST(TestCommand, testRemoveCommand) { cout << "testRemoveCommand" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* commandWriter = new CommandWriter(fos); RemoveCommand cmd; cmd.setDB("testdb"); cmd.setNameSpace("test.namespace.db"); std::string* uid = uuid(); cmd.setId(*uid); std::string* revision = uuid(); cmd.setRevision(*revision); commandWriter->writeCommand(&cmd); fos->close(); delete fos; delete commandWriter; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); RemoveCommand* rdCmd = (RemoveCommand*) reader->readCommand(); EXPECT_TRUE(rdCmd != NULL); EXPECT_TRUE(rdCmd->nameSpace()->compare("test.namespace.db") == 0); EXPECT_TRUE(rdCmd->DB()->compare("testdb") == 0); EXPECT_TRUE(rdCmd->id()->compare(*uid) == 0); EXPECT_TRUE(rdCmd->revision()->compare(*revision) == 0); delete fis; delete reader; delete rdCmd; }
TEST(TestCommand, testInsertCommand) { cout << "testInsertCommand" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* commandWriter = new CommandWriter(fos); InsertCommand cmd; cmd.setDB("testdb"); cmd.setNameSpace("test.namespace.db"); BSONObj* obj = new BSONObj(); obj->add("name", "Cross"); obj->add("age", 18); cmd.setBSON(obj); commandWriter->writeCommand(&cmd); fos->close(); delete fos; delete commandWriter; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); InsertCommand* rdCmd = (InsertCommand*) reader->readCommand(); EXPECT_TRUE(rdCmd != NULL); EXPECT_TRUE(rdCmd->nameSpace()->compare("test.namespace.db") == 0); EXPECT_TRUE(rdCmd->DB()->compare("testdb") == 0); const BSONObj* objResult = rdCmd->bson(); EXPECT_TRUE(objResult != NULL); EXPECT_TRUE(objResult->has("name")); EXPECT_TRUE(objResult->getString("name").compare("Cross") == 0); }
TEST(TestCommand, testFindCommand) { cout << "testFindCommand" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* commandWriter = new CommandWriter(fos); FindCommand cmd; cmd.setDB("testdb"); cmd.setNameSpace("test.namespace.db"); cmd.setSelect("*"); cmd.setFilter("$'a.b.c' == 1"); commandWriter->writeCommand(&cmd); fos->close(); delete fos; delete commandWriter; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); FindCommand* rdCmd = (FindCommand*) reader->readCommand(); EXPECT_TRUE(rdCmd != NULL); EXPECT_TRUE(rdCmd->select()->compare("*") == 0); EXPECT_TRUE(rdCmd->nameSpace()->compare("test.namespace.db") == 0); EXPECT_TRUE(rdCmd->DB()->compare("testdb") == 0); EXPECT_TRUE(rdCmd->filter()->compare("$'a.b.c' == 1") == 0); }
TEST(TestCommand, testUpdateCommand) { cout << "testUpdateCommand" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* commandWriter = new CommandWriter(fos); UpdateCommand cmd; cmd.setDB("testdb"); cmd.setNameSpace("test.namespace.db"); BSONObj obj; std::string* uid = uuid(); obj.add("_id", const_cast<char*>(uid->c_str())); delete uid; obj.add("name", "Cross"); obj.add("age", 18); cmd.setBSON(obj); commandWriter->writeCommand(&cmd); fos->close(); delete fos; delete commandWriter; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); UpdateCommand* rdCmd = (UpdateCommand*) reader->readCommand(); EXPECT_TRUE(rdCmd != NULL); EXPECT_TRUE(rdCmd->nameSpace()->compare("test.namespace.db") == 0); EXPECT_TRUE(rdCmd->DB()->compare("testdb") == 0); BSONObj* objResult = rdCmd->bson(); EXPECT_TRUE(objResult != NULL); EXPECT_TRUE(objResult->has("name")); EXPECT_TRUE(objResult->getString("name").compare("Cross") == 0); }
// protected void FileOutputStreamTestCase::write (void) { File f (TEST_FILE_NAME); if (f.exists ()) f.remove (); FileOutputStream out (TEST_FILE_NAME, CREATE_NEW_MODE); const char* str = "Test line 1\r\nTest line 2\r\nTest line 3"; out.write ((const unsigned char*)str, strlen (str)); out.close (); File ff (TEST_FILE_NAME); CPPUNIT_ASSERT (ff.getLength () == strlen (str)); File filer (TEST_FILE_NAME1); if (filer.exists ()) filer.remove (); FileOutputStream fout5(TEST_FILE_NAME1, APPEND_MODE); String s2 = "test line"; fout5.write ((unsigned char*)s2.getCStr (), s2.getLength ()); File filetest (TEST_FILE_NAME1); CPPUNIT_ASSERT (filetest.getLength () == s2.getLength ()); fout5.close (); }
TEST(testIndexP, generateNames) { // this will avoid overriding previously generated names and keep consistent the results if (!existFile("names.txt")) { FileInputStream* fisNames = new FileInputStream("names.csv", "r"); const char* fullNames = fisNames->readFull(); FileInputStream* fisLastNames = new FileInputStream("last.csv", "r"); const char* fullLast = fisLastNames->readFull(); std::vector<string> names = split(fullNames, "\r"); cout << names.size() << endl; std::vector<string> lastNames = split(fullLast, "\r"); cout << lastNames.size() << endl; FileOutputStream* fos = new FileOutputStream("names.txt", "w+"); for (int x = 0; x < 10000000; x++) { int i = rand() % names.size(); std::string name = names.at(i); i = rand() % lastNames.size(); std::string lastName = lastNames.at(i); std::string fullName = name + " " + lastName; fos->writeString(fullName); } fos->close(); fisNames->close(); fisLastNames->close(); delete fos; delete fisNames; delete fisLastNames; } }
// ================================================================================================================= bool DiskSampleRecorder::reserveDiskSpace(String outDir, int64 lengthInBytes) { String audioFileName(outDir); File* tempDataFile; Time now; if ( !audioFileName.endsWith(File::separatorString)) audioFileName += File::separatorString; for (int i=0; i < processorOutputs; i++) { now = Time::getCurrentTime(); tempDataFile = new File(audioFileName + "channel" + String::formatted("%.2d", i) + ".dat"); if (*tempDataFile == File::nonexistent) { mchaRecordPlayer->logError( L"Failed to reserve disk space for data file:\t" + tempDataFile->getFullPathName() ); delete tempDataFile; return false; } else { FileOutputStream* tempStream = tempDataFile->createOutputStream(); if (tempStream == NULL) { mchaRecordPlayer->logError( L"Failed to create output stream for data file:\t" + tempDataFile->getFullPathName() ); delete tempStream; delete tempDataFile; return false; } else { if (!tempStream->setPosition(lengthInBytes)) { mchaRecordPlayer->logError( L"Failed to position output stream for data file:\t" + tempDataFile->getFullPathName() + ". Insufficient disk space?" ); delete tempStream; delete tempDataFile; return false; } else { int zeroByte = 0; tempStream->write( (void *) &zeroByte, 1); tempStream->flush(); } } RelativeTime timeDelay = Time::getCurrentTime() - now; mchaRecordPlayer->dbgOut( "\tReserving disk space for\t" + tempDataFile->getFullPathName() + "\t" + String(lengthInBytes) + " bytes\t" + String(timeDelay.inSeconds())+ " s elapsed." ); delete tempStream; delete tempDataFile; } } return true; }
int Doc::Save( ArrayPtrVoid params ) { // param 0: output stream FileOutputStream *output = static_cast<FileOutputStream*>(params[0]); if (!output->WriteDoc( this )) { return FUNCTOR_STOP; } return FUNCTOR_CONTINUE; }
static void appendToFile (const File& f, const String& s) { if (f.getFullPathName().isNotEmpty()) { FileOutputStream out (f); if (! out.failedToOpen()) out << s << newLine; } }
Result saveDocument (const File& file) override { // attempt to save the contents into the given file FileOutputStream os (file); if (os.openedOk()) os.writeText (editor.getText(), false, false); return Result::ok(); }
void ApplicationSettingsFile::SaveAs(File file) { var json = toJSON(); FileOutputStream *outputStream = file.createOutputStream(); outputStream->setPosition(0); JSON::writeToStream(*outputStream, json); outputStream->flush(); delete outputStream; outputStream = nullptr; }
// protected void FileOutputStreamTestCase::close (void) { File ff (TEST_FILE_NAME); if (ff.exists () == false) ff.create (); FileOutputStream fout (TEST_FILE_NAME, OPEN_MODE); CPPUNIT_ASSERT (fout.seek (1, BEGIN_ORIGIN) == 1); fout.close (); }
Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles) { auto* zei = entries.getUnchecked (index); #if JUCE_WINDOWS auto entryPath = zei->entry.filename; #else auto entryPath = zei->entry.filename.replaceCharacter ('\\', '/'); #endif if (entryPath.isEmpty()) return Result::ok(); auto targetFile = targetDirectory.getChildFile (entryPath); if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\')) return targetFile.createDirectory(); // (entry is a directory, not a file) ScopedPointer<InputStream> in (createStreamForEntry (index)); if (in == nullptr) return Result::fail ("Failed to open the zip file for reading"); if (targetFile.exists()) { if (! shouldOverwriteFiles) return Result::ok(); if (! targetFile.deleteFile()) return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName()); } if (! targetFile.getParentDirectory().createDirectory()) return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName()); { FileOutputStream out (targetFile); if (out.failedToOpen()) return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName()); out << *in; } targetFile.setCreationTime (zei->entry.fileTime); targetFile.setLastModificationTime (zei->entry.fileTime); targetFile.setLastAccessTime (zei->entry.fileTime); return Result::ok(); }
// protected void FileOutputStreamTestCase::flush (void) { File file (_T("testflush")); if (file.exists ()) file.remove (); FileOutputStream fout (_T("testflush"), CREATE_NEW_MODE); fout.write ((unsigned char*)"1", 1); fout.flush (); CPPUNIT_ASSERT (file.getLength () == 1); fout.close (); file.remove (); }
HRESULT CFileHelper::WriteText(LPCTSTR path, LPCTSTR text) { BOOL exists = FALSE; HRESULT hr = Contains(path, exists); if(FAILED(hr)) return hr; if( !exists) { String folder ; if(SUCCEEDED( GetParentFolder(path, folder))) { hr = CreateFolder(folder.c_str()); if(FAILED(hr)) return hr; } } FileOutputStream ofs; ofs.imbue(locale("chs")); ofs.open(path); if(!ofs.is_open()) return E_FAIL; ofs.clear(); ofs.write(text, STRLEN(text)/* *sizeof(TCHAR)*/); ofs.close(); return S_OK; }
bool Tunefish4AudioProcessor::saveProgram(eU32 index) { String path = pluginLocation + File::separatorString + String("tf4programs") + File::separatorString + String("program") + String(index) + String(".txt"); File file(path); file.deleteFile(); FileOutputStream *stream = file.createOutputStream(); if (!stream) return false; stream->writeText(programs[index].getName(), false, false); stream->writeText("\r\n", false, false); for(eU32 i=0;i<TF_PARAM_COUNT;i++) { stream->writeText(TF_NAMES[i], false, false); stream->writeText(";", false, false); stream->writeText(String(programs[index].getParam(i)), false, false); stream->writeText("\r\n", false, false); } eDelete(stream); return true; }
TEST(TestCommand, testOptionsCommand) { cout << "testOptionsCommand" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* commandWriter = new CommandWriter(fos); BSONObj* options = new BSONObj(); std::string* txId = uuid(); options->add("_transactionId", const_cast<char*>(txId->c_str())); delete txId; InsertCommand cmd; cmd.setDB("testdb"); cmd.setNameSpace("test.namespace.db"); cmd.setOptions(options); BSONObj* obj = new BSONObj(); obj->add("name", "Cross"); obj->add("age", 18); cmd.setBSON(obj); commandWriter->writeCommand(&cmd); fos->close(); delete fos; delete commandWriter; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); InsertCommand* rdCmd = (InsertCommand*) reader->readCommand(); EXPECT_TRUE(rdCmd != NULL); EXPECT_TRUE(rdCmd->nameSpace()->compare("test.namespace.db") == 0); EXPECT_TRUE(rdCmd->DB()->compare("testdb") == 0); const BSONObj* objResult = rdCmd->bson(); EXPECT_TRUE(objResult != NULL); EXPECT_TRUE(objResult->has("name")); EXPECT_TRUE(objResult->getString("name").compare("Cross") == 0); EXPECT_TRUE(rdCmd->options() != NULL); if (rdCmd->options() != NULL) { const BSONObj* options = rdCmd->options(); EXPECT_TRUE(options->has("_transactionId")); } }
void FileLogger::trimFileSize (int64 maxFileSizeBytes) const { if (maxFileSizeBytes <= 0) { logFile.deleteFile(); } else { const int64 fileSize = logFile.getSize(); if (fileSize > maxFileSizeBytes) { TemporaryFile tempFile (logFile); { FileOutputStream out (tempFile.getFile()); FileInputStream in (logFile); if (! (out.openedOk() && in.openedOk())) return; in.setPosition (fileSize - maxFileSizeBytes); for (;;) { const char c = in.readByte(); if (c == 0) return; if (c == '\n' || c == '\r') { out << c; break; } } out.writeFromInputStream (in, -1); } tempFile.overwriteTargetFileWithTemporary(); } } }
bool File::copyInternal (const File& dest) const { FileInputStream in (*this); if (dest.deleteFile()) { { FileOutputStream out (dest); if (out.failedToOpen()) return false; if (out.writeFromInputStream (in, -1) == getSize()) return true; } dest.deleteFile(); } return false; }
// protected void FileOutputStreamTestCase::ctors (void) { File f1 (TEST_FILE_NAME); if (f1.exists () == false) f1.create (); // open mode FileOutputStream fout (TEST_FILE_NAME, OPEN_MODE); fout.close (); // open or create mode File file (TEST_FILE_NAME); FileOutputStream fout1 (file, OPEN_OR_CREATE_MODE); fout1.close (); // read_share FileOutputStream fout2(TEST_FILE_NAME, CREATE_MODE, READ_SHARE); fout2.close (); }
TEST(TestCommand, testShowdbs) { cout << "testShowdbs" << endl; FileOutputStream* fos = new FileOutputStream("test.dat", "wb"); CommandWriter* writer = new CommandWriter(fos); ShowdbsCommand cmd; writer->writeCommand(&cmd); fos->close(); delete fos; delete writer; FileInputStream* fis = new FileInputStream("test.dat", "rb"); CommandReader* reader = new CommandReader(fis); Command* resCmd = reader->readCommand(); EXPECT_TRUE(resCmd->commandType() == SHOWDBS); fis->close(); delete resCmd; delete fis; delete reader; }
// protected void FileOutputStreamTestCase::getCurrentOffset (void) { File ff (TEST_FILE_NAME); if (ff.exists () == false) ff.create (); FileOutputStream fout (TEST_FILE_NAME, OPEN_MODE); String ss = "dflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdja sd"; fout.write ((unsigned char *)ss.getCStr (), ss.getLength ()); fout.flush (); fout.seek (3, BEGIN_ORIGIN) ; CPPUNIT_ASSERT (fout.getCurrentOffset ()== 3); fout.seek (3, CURRENT_ORIGIN) ; CPPUNIT_ASSERT (fout.getCurrentOffset ()== 6); fout.seek (-2, CURRENT_ORIGIN) ; CPPUNIT_ASSERT (fout.getCurrentOffset ()== 4); }
void writeFile(File const& file) { Logger *log = Logger::getCurrentLogger(); FileOutputStream stream (file); if(!stream.openedOk()) { log->writeToLog("failed to open stream"); return; } stream.setPosition(0); stream.truncate(); stream.writeInt(1234); stream.writeFloat(3.142); stream.writeDouble(0.00001234); }
// test function for expressions int main() { ProductExpression *expression = new ProductExpression( new PowerExpression( new ConstantExpression( 5 ), new ConstantExpression( 6 ) ), new NegateExpression( new SinExpression( new ConstantExpression( 19 ) ) ) ); InvertExpression *invExpression = new InvertExpression( expression ); SumExpression *sumExpression = new SumExpression( invExpression, new ConstantExpression( 2 ) ); sumExpression->print(); printf( "\n" ); printf( "%f\n", sumExpression->evaluate() ); printf( "Writing to file.\n" ); char **pathSteps = new char*[2]; pathSteps[0] = new char[10]; pathSteps[1] = new char[10]; sprintf( pathSteps[0], "test" ); sprintf( pathSteps[1], "file" ); int *stepLength = new int[2]; stepLength[0] = 4; stepLength[1] = 4; Path *path = new Path( pathSteps, 2, stepLength, false ); File *file = new File( path, "test.out", 8 ); FileOutputStream *outStream = new FileOutputStream( file, false ); char *error = outStream->getLastError(); if( error != NULL ) { printf( "Error: %s\n", error ); delete error; } ExpressionSerializer::serializeExpression( sumExpression, outStream ); delete outStream; delete file; printf( "Reading back in from file.\n" ); pathSteps = new char*[2]; pathSteps[0] = new char[10]; pathSteps[1] = new char[10]; sprintf( pathSteps[0], "test" ); sprintf( pathSteps[1], "file" ); stepLength = new int[2]; stepLength[0] = 4; stepLength[1] = 4; path = new Path( pathSteps, 2, stepLength, false ); file = new File( path, "test.out", 8 ); FileInputStream *inStream = new FileInputStream( file ); error = inStream->getLastError(); if( error != NULL ) { printf( "Error: %s\n", error ); delete error; } Expression *readExpression; ExpressionSerializer::deserializeExpression( &readExpression, inStream ); delete inStream; delete file; readExpression->print(); printf( "\n" ); printf( "%f\n", readExpression->evaluate() ); delete sumExpression; delete readExpression; return 0; }
void HeightMap::convert(const String& path) { FileInputStream* reader = NULL; try { reader = new FileInputStream(new File(path)); } catch (...) { System::out << "could not open reader" << endl; exit(1); } FileOutputStream* writer = NULL; try { writer = new FileOutputStream(new File("converted_" + path)); } catch (...) { System::out << "could not open writer" << endl; exit(1); } //FileOutputStream* writer = new FileOutputStream(new File("converted_" + path)); byte emptybuffer[PLANEWIDTH * HEIGHTSIZE]; for (int i = 0; i < PLANEWIDTH * HEIGHTSIZE; ++i) emptybuffer[i] = 0; // first 2 lines for (int i = 0; i < 2 * 64; ++i) { for (int j = 0; j < PLANEWIDTH; ++j) writer->write(emptybuffer, PLANEWIDTH * HEIGHTSIZE); } int planeIndexX = 2; int planeIndexY = 2; // inner 60 lines for (int i = 0; i < 60; ++i) { // 2 beginning plane for (int j = 0; j < 2 * PLANEWIDTH; ++j) writer->write(emptybuffer, PLANEWIDTH * HEIGHTSIZE); // inner 60 planes for (int j = 0; j < 60; ++j) { System::out << "\r writing(" << planeIndexX << ", " << planeIndexY << ")"; float plane[PLANEWIDTH * PLANEWIDTH]; readPlaneForConversion(reader, plane, planeIndexX - 2, planeIndexY - 2); writer->write((byte*) plane, PLANEWIDTH * PLANEWIDTH * HEIGHTSIZE); ++planeIndexX; } planeIndexX = 2; ++planeIndexY; // 2 ending plane for (int j = 0; j < 2 * PLANEWIDTH; ++j) writer->write(emptybuffer, PLANEWIDTH * HEIGHTSIZE); } //last 2 lines for (int i = 0; i < 2 * 64; ++i) { for (int j = 0; j < PLANEWIDTH; ++j) writer->write(emptybuffer, PLANEWIDTH * HEIGHTSIZE); } writer->close(); delete writer; delete reader; }
// protected void FileOutputStreamTestCase::seek (void) { File ff (TEST_FILE_NAME); if (ff.exists () == false) ff.create (); FileOutputStream fout (TEST_FILE_NAME, OPEN_MODE); String ss = "dflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdjadflajdkjasldjfaksldjfsalkdjalksdja sd"; fout.write ((unsigned char *)ss.getCStr (), ss.getLength ()); fout.flush (); CPPUNIT_ASSERT_THROW (fout.seek (-1, BEGIN_ORIGIN), Exception); CPPUNIT_ASSERT (fout.seek (3, BEGIN_ORIGIN) == 3); CPPUNIT_ASSERT (fout.seek (21, BEGIN_ORIGIN) == 21); CPPUNIT_ASSERT (fout.seek (38, BEGIN_ORIGIN) == 38); CPPUNIT_ASSERT (fout.seek (-7, CURRENT_ORIGIN) == 31); CPPUNIT_ASSERT (fout.seek (2, CURRENT_ORIGIN) == 33); CPPUNIT_ASSERT_THROW (fout.seek (-73, CURRENT_ORIGIN), Exception); CPPUNIT_ASSERT (fout.seek (24, CURRENT_ORIGIN) == 57); CPPUNIT_ASSERT (fout.seek (24, CURRENT_ORIGIN) == 81); fout.close (); }
int main( char inNumArgs, char **inArgs ) { if( inNumArgs < 2 ) { usage( inArgs[0] ); } if( inNumArgs > 3 ) { usage( inArgs[0] ); } char useFile = true; if( inNumArgs != 3 ) { useFile = false; } long port; int numRead = sscanf( inArgs[1], "%d", &port ); if( numRead != 1 ) { printf( "port number must be a valid integer: %s\n", inArgs[2] ); usage( inArgs[0] ); } File *outFile; FileOutputStream *outStream; if( useFile ) { outFile = new File( NULL, inArgs[2], strlen( inArgs[2] ) ); outStream = new FileOutputStream( outFile ); } SocketServer *server = new SocketServer( port, 1 ); printf( "listening for a connection on port %d\n", port ); Socket *sock = server->acceptConnection(); if( sock == NULL ) { printf( "socket connection failed\n" ); return( 1 ); } printf( "connection received\n" ); SocketStream *inStream = new SocketStream( sock ); unsigned long checksum = 0; unsigned char *buffer = new unsigned char[ BUFFER_SIZE ]; numRead = BUFFER_SIZE; int numWritten = BUFFER_SIZE; while( numWritten == numRead && numRead == BUFFER_SIZE ) { // read a buffer full of data from standard in numRead = inStream->read( buffer, BUFFER_SIZE ); // add the buffer to our checksum for( int i=0; i<numRead; i++ ) { checksum += buffer[i]; } if( useFile ) { // write the buffer out to our file stream numWritten = outStream->write( buffer, numRead ); } else { // write to std out numWritten = fwrite( buffer, 1, numRead, stdout ); } } if( numRead != numWritten ) { printf( "file output failed\n" ); } printf( "checksum = %d\n", checksum ); delete sock; delete server; delete inStream; if( useFile ) { delete outStream; delete outFile; } delete [] buffer; return 0; }