// load in a set of (const, beta, temp) values void load_cbt(std::string& filename, vecvec& cbt, int ndata) { std::ifstream input_file(filename.c_str()); cbt.resize(ndata); for (int i = 0; i < ndata; ++i) { std::vector<double> this_cbt(3); for (int j = 0; j < 3; ++j) { input_file >> this_cbt[j]; } cbt[i] = this_cbt; } input_file.close(); }
void trokam::file_management::get_file_contents(const std::string &file_name, std::string &content) { std::ifstream input_file(file_name.c_str(), std::ios::in | std::ios::binary); if(input_file) { input_file.seekg(0, std::ios::end); content.resize(input_file.tellg()); input_file.seekg(0, std::ios::beg); input_file.read(&content[0], content.size()); input_file.close(); } }
void FileHelp::copy_file(const std::string &from, const std::string &to, bool copy_always) { #ifdef WIN32 BOOL result = CopyFile(StringHelp::utf8_to_ucs2(from).c_str(), StringHelp::utf8_to_ucs2(to).c_str(), copy_always ? FALSE : TRUE); if (result == FALSE) throw Exception("Unable to copy file"); #else while (!copy_always) { try { File input_file(to); } catch (const Exception&) { break; } throw Exception("Destination file already exists"); } File input_file(from); File output_file(to, File::create_always, File::access_read_write); char buffer[16*1024]; while (true) { int bytes_read = input_file.read(buffer, 16*1024); if (bytes_read <= 0) break; int bytes_written = output_file.write(buffer, bytes_read); if (bytes_written != bytes_read) { output_file.close(); FileHelp::delete_file(to); throw Exception("Unable to copy file"); } } #endif }
// The main program: int main(int argc, char* argv[]) { Polygon_2 polygon; const char* filename = (argc > 1) ? argv[1] : "polygon.dat"; std::ifstream input_file(filename); if (! input_file.is_open()) { std::cerr << "Failed to open the " << filename << std::endl; return -1; } input_file >> polygon; input_file.close(); // Example for is_pullout_direction_single_mold_translational_casting_2 that // accepts the edge size_t index(0); for (auto e_it = polygon.edges_begin(); e_it != polygon.edges_end(); ++e_it, ++index) { auto orientation = polygon.orientation(); auto segment_outer_circle = SMS::internal::get_segment_outer_circle<Kernel>(*e_it, orientation); auto d = segment_outer_circle.first; d = d.perpendicular(CGAL::CLOCKWISE); auto res = casting::is_pullout_direction(polygon, e_it, d); std::cout << "The polygon is " << (res ? "" : "not ") << "castable using edge " << index << " in vartical translation (" << d << ")" << std::endl; } std::cout << "-----------------------------------"<< std::endl; // Example for is_pullout_direction_single_mold_translational_casting_2 that // do not accepts the edge { Vector_2 v (Point_2(0,0), Point_2(1,0)); Direction_2 d(v); auto res = casting::is_pullout_direction(polygon, d); if (res != polygon.edges_end()) { std::cout << "The polygon is castable in direction d (" << d << ") using edge "<< *res << std::endl; } else { std::cout << "The polygon is not castable in direction d (" << d << ")" << std::endl; } } return 0; }
int SiteMan::parse(const char* filename){ std::string line; std::ifstream input_file (filename); int line_count = 0; int ret = 0; // open file if (!input_file.is_open()) { return 1; } if (!getline(input_file, line)) { return 1; } line_count++; // parse first line (dimensions) std::vector<std::string> dim = split(line, ' '); this->nb_to_build = atoi(dim[1].c_str()); std::cout << "Dimensions: " << dim[0] << ", " << this->nb_to_build << std::endl; // parse other lines (datas) while (getline(input_file, line)) { // got the line line_count++; // parse it std::vector<std::string> site_data = split(line, ' '); // check errors if (site_data.size() < 4) { std::cerr << "Syntax error on line " << line_count << ": only " << site_data.size() << " items on the line" << std::endl; ret = 1; continue; } else { std::cout << "New site ! Id=" << site_data[0] << ", pos=(" << site_data[1] << "," << site_data[2] << "), capacity=" << site_data[3] << std::endl; } this->sites->push_back(new Site( atoi(site_data[0].c_str()), atoi(site_data[1].c_str()), atoi(site_data[2].c_str()), atoi(site_data[3].c_str()), false)); } return ret; }
QByteArray IOFactory::readFile(const QString& file_path) { QFile input_file(file_path); QByteArray input_data; if (input_file.open(QIODevice::Text | QIODevice::Unbuffered | QIODevice::ReadOnly)) { input_data = input_file.readAll(); input_file.close(); return input_data; } else { throw IOException(tr("Cannot open file '%1' for reading.").arg(QDir::toNativeSeparators(file_path))); } }
void ParticleGenerator::getFileInput(char* fileName, ParticleContainer* pc, Simulation *sim) { double m = 1; int num_cuboids = 0; std::ifstream input_file(fileName); string tmp_string; if (input_file.is_open()) { getline(input_file, tmp_string); LOG4CXX_DEBUG(iolog, "Read line: " << tmp_string); while (tmp_string.size() == 0 || tmp_string[0] == '#') { getline(input_file, tmp_string); LOG4CXX_DEBUG(iolog, "Read line: " << tmp_string); } istringstream numstream(tmp_string); numstream >> num_cuboids; LOG4CXX_DEBUG(iolog, "Reading " << num_cuboids << "."); getline(input_file, tmp_string); LOG4CXX_DEBUG(iolog, "Read line: " << tmp_string); for (int i = 0; i < num_cuboids; i++) { istringstream datastream(tmp_string); for (int j = 0; j < 3; j++) { datastream >> X[j]; } for (int j = 0; j < 3; j++) { datastream >> V[j]; } for (int j = 0; j < 3; j++) { datastream >> num[j]; } if (datastream.eof()) { LOG4CXX_ERROR(iolog, "Error reading file: eof reached unexpectedly reading from line " << i); exit(-1); } datastream >> meanV; datastream >> M; datastream >> H; // create particles from cuboid data LOG4CXX_ERROR(particlelog, "Generating Cuboid..."); createParticles(pc); getline(input_file, tmp_string); } } else {
int main(int argc, char *argv[]) { // Paso por parametro del valor de M if(argc > 1){ M = atoi(argv[1]); //printf("Running with M = %d\n", M); } else{ //printf("Running with default M = 10000\n"); } // Los vectores en C++ son escencialmente arreglos en C con una interfaz // más conveniente. Donde sea que se pueda usar arreglos, se puede usar // vectores. Cuando se necesita la dirección de memoria de un arreglo, hay // que usar la dirección del primer elemento del vector: &x[0]. x por sí // solo no sirve ya que es un objeto que encapsula al verdadero arreglo. std::vector<float> x1; x1.reserve(N); x1.resize(N); // copiar datos del archivo de entrada al vector std::ifstream input_file(data_file_name, std::ios::binary | std::ios::in); if (!input_file) { std::cerr << "No se pudo abrir el archivo " << data_file_name << std::endl; std::exit(-1); } input_file.read((char *) &x1[0], N * sizeof(float)); input_file.close(); // crear una copia del vector, de modo de tener // uno para mapear en la GPU y otro en la CPU std::vector<float> x2(x1); // mapear x1 en la CPU y x2 en la GPU cpu_map(x1, M); gpu_map(&x2[0], x2.size(), M); // verificar que los resultados son prácticamente iguales float squared_diff_norm = 0.0; # define SQUARED(x) ((x) * (x)) # pragma omp parallel reduction(+: squared_diff_norm) for (unsigned i = 0; i < N; ++i) squared_diff_norm += SQUARED(x1[i] - x2[i]); // Comentar para tests //std::cout << "Norma de la diferencia: " << std::sqrt(squared_diff_norm) << std::endl; // Descomentar para tests std::cout << std::sqrt(squared_diff_norm) << std::endl; }
std::string trokam::file_management::get_file_contents(std::string filename) { std::string content; std::ifstream input_file(filename.c_str(), std::ios::in | std::ios::binary); if(input_file) { input_file.seekg(0, std::ios::end); content.resize(input_file.tellg()); input_file.seekg(0, std::ios::beg); input_file.read(&content[0], content.size()); input_file.close(); } return(content); }
int main(int argc, char * argv[]) { Sales_data just_isbn_book("123456789-D"); //test usage of partial constructor.OK it compiles print(cout , just_isbn_book) ; cout << endl; Sales_data full_book("123456789-F", 3, 38.8, "Effective C++"); //test usage of full constructor.OK it compiles print(cout , full_book) ; cout << endl; cout << "\tAfter testing the 2 constructors, we read form the file supplied in the command line " << endl; if(argc == 1) //input file name passed with redirection < filename { Sales_data total(cin); //using the constructor for initialization: reading input e.g. from a file, or from console if( !total.isbn().empty() ) { Sales_data trans; // variable to hold data for the next transaction while( read(cin, trans) ) { if ( total.isbn() == trans.isbn() ) total.combine(trans); else { print(cout , total ) ; cout<<endl; total = trans ; } } print( cout, total ) ; cout<<endl; } else std::cerr << "No data?!" << endl; } else if (argc == 2) // input file passed as command line arg { ifstream input_file(argv[1]); Sales_data total; if (read(input_file, total)) { // read the first transaction Sales_data trans; // variable to hold data for the next transaction while(read(input_file, trans)) { // read the remaining transactions if (total.isbn() == trans.isbn()) // check isbn s total.combine(trans); // update the running total else { print(cout, total) << endl; // print the results total = trans; // process the next book } } print(cout, total) << endl; // print the last transaction } else // there was no input cerr << "No data?!" << endl; } return 0; }
int AL_PROTO ALCompressedObject::Extract( ALStorage AL_DLL_FAR &output_object ) { long compressed_length; long crc32; AL_ASSERT_OBJECT( this, ALCompressedObject, "Extract" ); AL_ASSERT_OBJECT( &output_object, ALStorage, "Extract" ); if ( mStatus < AL_SUCCESS ) return mStatus; // // Open the input file. // ALOpenInputFile input_file( *mpStorageObject ); // // Now read in all the data stored at the start of the object, // including any header data created by derived classes. If we are // using the base class, there won't be any additional data bytes there. // mpStorageObject->ReadPortableLong( output_object.mlSize ); mpStorageObject->ReadPortableLong( compressed_length ); mpStorageObject->ReadPortableLong( crc32 ); ReadHeaderData( &output_object ); if ( mpStorageObject->mStatus < 0 ) return mStatus = mpStorageObject->mStatus; // // Open the output file. // ALOpenOutputFile output_file( output_object ); // // Extract the data and store it in the storage object specified // as an argument. // if ( mpCompressionEngine->Decompress( *mpStorageObject, output_object, compressed_length ) < 0 ) return mStatus = mpCompressionEngine->mStatus; // // A little error checking leads to an error return if things didn't // go well, or AL_SUCCESS if things did. // if ( mpStorageObject->mStatus < 0 ) return mStatus = mpStorageObject->mStatus; if ( crc32 != ~output_object.GetCrc32() ) return mStatus.SetError( AL_CRC_ERROR, "CRC32 differs between %s and %s", mpStorageObject->mName.GetName(), output_object.mName.GetName() ); return AL_SUCCESS; }
int main (int argc, char *argv[]) { std::ifstream input_file(argv[1]); // open the input file unsigned long long seiveRange = 4967295; bool array[seiveRange + 1]; SieveOfEratosthenes(array, seiveRange + 1); unsigned long long N; while(input_file) { input_file >> N; printf("2"); for (unsigned long long i = 3; i < N; i++) if (array[i]) printf(",%llu",i); printf("\n"); } }
void ndiSerialClose(long serial_port) { int i; /* restore the comm port state to from before it was opened */ for (i = 0; i < NDI_MAX_SAVE_STATE; i++) { if (ndi_open_handles[i] == serial_port && ndi_open_handles[i] != -1) { ndi_open_handles[i] = -1; break; } } CloseDriver(input_file(serial_port)); CloseDriver(output_file(serial_port)); }
bool extract_tokens_from_file(std::string file_name, evl_tokens &tokens) { // use reference to modify it std::ifstream input_file(file_name.c_str()); if (!input_file){ std::cerr << "I can't read " << file_name << "." << std::endl; return false; } tokens.clear(); std::string line; for (int line_no = 1; std::getline(input_file, line); ++line_no){ if (!extract_tokens_from_line(line, line_no, tokens)) { return false; } } return true; }
PhaseDetector::PhaseDetector(std::string input_filename, unsigned int max_phase_sz, unsigned int elems_to_read) : max_phase_size(max_phase_sz), max_elems(elems_to_read), has_new_phase(false) { std::ifstream input_file(input_filename); std::vector<int64_t> line_values; std::string input_str; if(input_file) { ///reading the number of entries and the number of iterators std::getline(input_file, input_str, ' '); entries_num = std::stol(input_str); std::getline(input_file, input_str); iterator_num = std::stol(input_str); ///reading the iterators' bounds for(unsigned int i = 0; i < iterator_num - 1; i++) { std::getline(input_file, input_str, ' '); bounds.insert(bounds.begin(),std::stol(input_str)); } std::getline(input_file, input_str); bounds.insert(bounds.begin(), std::stol(input_str)); ///reading the memory positions and their corresponding iteration vectors for(unsigned int i = 0; i < max_elems; i++) { std::getline(input_file, input_str,'\n'); if(input_file.eof()) break; line_values = splitEntry(input_str); std::vector<int64_t> iterators(line_values.begin() + 1, line_values.end()); addr_vector.push_back(line_values[0]); iterators_vector.push_back(iterators); } next_start = 0; } else { cerr << "Couldn't open the input file\n"; exit(EXIT_FAILURE); } input_file.close(); }
std::vector<uint8_t> LoadFromFileAndDecompress(const std::string& path) { std::ifstream input_file(path, std::ios::binary | std::ios::in | std::ios::ate); if (!input_file.is_open()) { throw_arc_exception(std::runtime_error, "Couldn't open file " + path); } std::streamsize size = input_file.tellg(); input_file.seekg(0, std::ios::beg); std::vector<uint8_t> file_buffer((size_t)size); if (!(input_file.read(reinterpret_cast<char*>(file_buffer.data()), size))) { throw_arc_exception(std::runtime_error, "Unable to read entire contents of file"); } const std::vector<uint8_t> decompressed = DecompressBytes(file_buffer); return decompressed; }
int main(void) { std::ifstream input_file(input_file_path.c_str()); if(!input_file) { std::cerr << "error: unable open input file: " << input_file_path << std::endl; return -1; } std::map< std::string, std::vector< std::string > > map_lastname; std::string lastname,firstname; std::string line; while(getline(input_file, line)) { std::vector<std::string> vec_name; std::istringstream oss(line); oss >> lastname; while(oss >> firstname) { vec_name.push_back(firstname); } map_lastname.insert(make_pair(lastname, vec_name)); } std::map< std::string, std::vector< std::string> >::const_iterator ret; std::vector< std::string >::const_iterator iter; while(std::cin >> lastname) { ret = map_lastname.find(lastname); if(ret == map_lastname.end()) { std::cout << "There is not the lastname: " << lastname << std::endl; } else { iter = ret -> second.begin(); while(iter != ret -> second.end()) { std::cout << *iter++ << '\t'; } std::cout << std::endl; } } return 0; }
// read in the data void read_data(std::string& filename, vecvec& meas, vecvec& meas_unc, int ndata, int mfeat) { std::ifstream input_file(filename.c_str()); meas.resize(ndata); meas_unc.resize(ndata); std::string header_line; std::getline(input_file, header_line); // read the header line for (int i = 0; i < ndata; ++i) { std::vector<double> this_meas(mfeat); std::vector<double> this_meas_unc(mfeat); for (int j = 0; j < mfeat; ++j) { input_file >> this_meas[j] >> this_meas_unc[j]; } meas[i] = this_meas; meas_unc[i] = this_meas_unc; } input_file.close(); }
void MatchSet :: read_from_file( string filename ){ ifstream input_file( filename.c_str() ); size_t num_matches; input_file >> num_matches; for( size_t i = 0; i < num_matches; i++ ){ PointT pt_c; PointT pt_r; float strength; int ref_idx; input_file >> pt_c.first >> pt_c.second >> pt_r.first >> pt_r.second >> strength >> ref_idx; add_match( pt_c, pt_r, strength, ref_idx ); } input_file.close(); }
// Parses an input file. bool parse_input_file(char* fname, std::string& input) { std::ifstream input_file(fname); if (input_file.is_open()) { std::string buf; while (getline(input_file, buf)) { input += buf; input += '\n'; buf.clear(); } input_file.close(); return true; } else return false; }
/*Read the set cover instance from a file*/ SCP_instance::SCP_instance(string input_file_path) { rows = new vector<set<int> >; columns = new vector<set<int> >; ifstream input_file(input_file_path.c_str()); input_file >> number_of_rows; rows->resize(number_of_rows); int tmp_int; set<int> tmp_column; int current_column_id = 0; while (input_file >> tmp_int) { if (tmp_int == -1) { columns->push_back(tmp_column); tmp_column.clear(); current_column_id = current_column_id + 1; } else { (*rows)[tmp_int].insert(current_column_id); tmp_column.insert(tmp_int); } } input_file.close(); number_of_columns = columns->size(); column_chosen = new bool[number_of_columns]; column_excluded = new bool[number_of_columns]; row_covered = new bool[number_of_rows]; row_excluded = new bool[number_of_rows]; for (int ii=0 ; ii < number_of_columns; ii++) { column_chosen[ii] = false; column_excluded[ii] = false; } for (int ii = 0; ii < number_of_rows; ii++) { row_covered[ii] = false; row_excluded[ii] = false; } lower_bound = 0; consistency_checking(); };
int main( int, char** ) { std::ifstream input_file( "../file_io/file.txt" ); if( input_file.is_open() ) { std::string input_line; while( getline( input_file, input_line) ) { std::vector< std::string > strings; std::split( input_line, ' ', strings ); std::cout << "Price: " << get_price( input_line ) << " " << "Barcode: " << get_barcode( input_line ) << std::endl; } input_file.close(); } return 0; }
void ConvertFileDialog::convertSlot() { if (!Converter::loaded()) { QMessageBox::critical(this, tr("OpenCC"), tr("Failed to load opencc.")); return; } QString input_file_name = ui->leInput->text(); QFile input_file(input_file_name, this); if (!input_file.open(QFile::ReadOnly)) { QMessageBox::critical(this, tr("OpenCC"), tr("Input file not readable.")); return; } input_file.close(); QString output_file_name = ui->leOutput->text(); QFile output_file(output_file_name, this); if (!output_file.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("OpenCC"), tr("Output file not writable.")); return; } QString config_file = ui->cbConfig->itemData(ui->cbConfig->currentIndex()).toString(); QByteArray config_file_utf8 = config_file.toUtf8(); Converter conv(config_file_utf8.data()); if (!conv.config_loaded()) { QMessageBox::critical(this, tr("OpenCC"), tr("Failed to load opencc configuration.")); return; } QString txt_in = textreader->readAll(input_file_name); QString txt_out = conv.convert(txt_in); QByteArray txt_out_utf8 = txt_out.toUtf8(); output_file.write(txt_out_utf8); output_file.close(); QMessageBox::information(this, tr("OpenCC"), tr("Successfully converted.")); }
////////////////////////////////// // Read the verifier output (from hardware execution) and display the results ////////////////////////////////// void verify_miss_rate(const std::string kernelname, const std::string benchname) { std::string filename = output_dir+"/"+benchname+"/"+kernelname+".prof"; // Test if the file exists std::ifstream exists_file(filename); if (!exists_file) { message("No verifier data information available, skipping verification"); return; } // Parse the file line by line unsigned counter = 0; unsigned long data; unsigned long miss = 0; unsigned long hit = 0; std::ifstream input_file(filename); while (input_file >> data) { if (counter == 0) { hit = data; } if (counter == 1) { miss = data; } counter++; } // Prepare to append to the output file std::ofstream file; file.open(output_dir+"/"+benchname+"/"+kernelname+".out", std::fstream::app); file << std::endl; // Output verification data to stdout message("Cache miss rate according to verification data:"); float miss_rate = 100*miss/(double)(miss+hit); std::cout << "### \t Total accesses: " << (miss+hit) << std::endl; std::cout << "### \t Misses: " << miss << std::endl; std::cout << "### \t Hits: " << hit << std::endl; std::cout << "### \t Miss rate: " << miss_rate << "%" << std::endl; // Output verification data to file file << "verified_misses: " << miss << std::endl; file << "verified_hits: " << hit << std::endl; file << "verified_miss_rate: " << miss_rate << std::endl; // Close the output file file.close(); }
std::uint32_t split_into_chunks(const std::string& filename, std::uint64_t chunk_size) { std::ifstream input_file(filename, std::ios::binary); uint32_t chunks_count = 0; char* buffer = new char[chunk_size]; while (!input_file.eof()) { input_file.read(buffer, chunk_size); auto read_length = input_file.gcount(); if (read_length > 0) { auto chunk_filename = get_chunk_filename(chunks_count++); std::ofstream chunk_file(chunk_filename, std::ios::binary | std::ios::trunc); chunk_file.write(buffer, read_length); chunk_file.close(); } } delete [] buffer; return chunks_count; }
////////////////////////////////// // Function to read the hardware settings from a file ////////////////////////////////// Settings get_settings(void) { std::string filename = config_dir+"/"+"current.conf"; // Test if the file exists std::ifstream exists_file(filename); if (!exists_file) { std::cout << "### Error: could not read settings file '" << filename << "'" << std::endl; message(""); exit(0); } // Open the settings file for reading std::ifstream input_file(filename); // Then proceed to the parse the data std::string identifier; unsigned line_size, cache_bytes, cache_ways, num_mshr, mem_latency, mem_latency_stddev; input_file >> identifier >> line_size; input_file >> identifier >> cache_bytes; input_file >> identifier >> cache_ways; input_file >> identifier >> num_mshr; input_file >> identifier >> mem_latency; input_file >> identifier >> mem_latency_stddev; // Store the data in the settings data-structure Settings hardware = { line_size, cache_bytes, cache_bytes/line_size, cache_ways, cache_bytes/(line_size*cache_ways), num_mshr, NUM_CORES, WARP_SIZE, MAX_ACTIVE_THREADS, MAX_ACTIVE_BLOCKS, mem_latency, mem_latency_stddev }; // Close the file and return return hardware; }
int main(int argc, char** argv) { // float f1 = 1.f, f2 = 2.f, f3 = 3.f; // qlnet::NodeOutputRefs<float> inputs = { f1, f2, f3 }; // qlnet::Node<float, qlnet::TransferFunc<float>::Linear> node; // qlnet::NodeOutputRef<float> node_output = node.output(); // node.connect(inputs); // node.init_weights({ 1, 1, 1 }); // node.update(); qlnet::PatternSet<int> *patterns = new qlnet::PatternSet<int>(); std::string input_file("sets/and2"); if(!patterns->read(input_file)) std::cout << "error: cannot read " << input_file << "\n"; else std::cout << "patters#: " << patterns->size() << " inputs#: " << patterns->input_size() << " outputs#: " << patterns->output_size() << "\n"; return 0; }
// // FUNCTION: FileContextMenuExt::InvokeCommand // // PURPOSE: This method is called when a user clicks a menu item to tell // the handler to run the associated command. The lpcmi parameter // points to a structure that contains the needed information. // IFACEMETHODIMP FileContextMenuExt::InvokeCommand(LPCMINVOKECOMMANDINFO pici) { HANDLE file = NULL; BY_HANDLE_FILE_INFORMATION fileInfo; SYSTEMTIME time; myFile temp; LISTF fileList; std::wofstream input_file("file.txt"); for (LISTWCS::iterator i = names.begin(); i != names.end(); ++i){ file = CreateFileW(i->c_str(), 0x00, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file != INVALID_HANDLE_VALUE) { if (GetFileInformationByHandle(file, &fileInfo)) { if (FileTimeToSystemTime(&fileInfo.ftCreationTime, &time)){ std::wstring fileName(i->c_str()); wcscpy_s(temp.name, fileName.substr(fileName.find_last_of(L"\\") + 1, fileName.length()).c_str()); temp.date = time; temp.size = fileInfo.nFileIndexLow; fileList.push_back(temp); } } CloseHandle(file); } } fileList.sort([](const myFile & a, const myFile & b) { //std::wstring A(a.name); //std::wstring B(b.name); return a.name < b.name; }); for (LISTF::iterator i = fileList.begin(); i != fileList.end(); ++i){ input_file << i->name << "\n" << i->date.wDay << "." << i->date.wMonth << "." << i->date.wYear << "\nSize: " << i->size<<"B \n\n"; } input_file.close(); return S_OK; }
void FileStorage::updateStudent(Student s){ string search_string = to_string(s.getId()); string replace_string = search_string +" " + s.getPass() + " " + s.getName() + " "; for (vector<string>::size_type i = 0; i != s.getCompleteCourses().size(); i++) { replace_string += s.getCompleteCourses()[i] + " "; } replace_string += " $ " + to_string(s.getPoints()+6); //+6 points!!! string inbuf; fstream input_file(this->file_name, ios::in); ofstream output_file("result.txt"); //Check for Error if (input_file.fail()){ cerr << "Error Opening Data File"; exit(1); } while (!input_file.eof()){ getline(input_file, inbuf); int spot = inbuf.find(search_string); if (spot >= 0){ string tmpstring = inbuf.substr(0, spot); tmpstring += replace_string; tmpstring += inbuf.substr(spot + inbuf.length(), inbuf.length()); inbuf = tmpstring; } output_file << inbuf << endl; } input_file.close(); output_file.close(); int result; char oldname[] = "result.txt"; char newname[] = "data.txt"; remove(newname); result = rename(oldname, newname); if (result == 0) puts("File successfully updated\n"); else perror("Student update error: Error renaming file\n"); }
int main( int argc, char* argv[] ) { setlocale(LC_ALL, ".1251"); std::ifstream input_file( BINARY_DIR "/input1.txt" ); std::vector<std::string> strings; std::string chars(" -\\"); if(input_file) { while( !input_file.eof() ) { std::string line; std::getline( input_file, line ); for(auto i = 0; i < chars.length(); i++) { line.erase(std::remove(line.begin(), line.end(), chars.c_str()[i]), line.end()); } std::transform(line.begin(), line.end(), line.begin(), ::tolower); if(strings.size() > 0) std::reverse(line.begin(), line.end()); strings.push_back(line); } input_file.close(); std::ofstream output_file( BINARY_DIR "/output1.txt" ); for(auto it = strings.begin() + 1; it != strings.end(); it++) { if(strings.at(0).find(*it) == std::string::npos) output_file << "NO" << std::endl; else output_file << "YES" << std::endl; } output_file.close(); } }