StdHandleSaver(const char* in, const char* out) : cin(std::cin.rdbuf()), cout(std::cout.rdbuf()), cerr(std::cerr.rdbuf()), clog(std::clog.rdbuf()), csh(in, out), // NOTE: Using undocumented constructor accepting FILE* // Only constructor accepts FILE* and swap is specified since C++11, so we need to use constructor ifs(stdin), ofs(stdout) { std::cin.rdbuf(ifs.rdbuf()); std::cout.rdbuf(ofs.rdbuf()); std::cerr.rdbuf(ofs.rdbuf()); std::clog.rdbuf(ofs.rdbuf()); }
File_Ops::File_Ops() : m_username("username"), m_appdata_path("./") { /** Redirect output **/ static std::ofstream cerr_file("stderr.txt"); static std::ofstream cout_file("stdout.txt"); if(cerr_file.is_open()) { cerr_bak = std::cerr.rdbuf(); std::cerr.rdbuf(cerr_file.rdbuf()); } if(cout_file.is_open()) { cout_bak = std::cout.rdbuf(); std::cout.rdbuf(cout_file.rdbuf()); } /** Get username **/ #ifdef _WINDOWS char username[MAX_PATH]; DWORD username_len = sizeof(username); if(!GetUserName(username, &username_len)) throw File_Ops_Init_Failure(); #else passwd * const pws = getpwuid(geteuid()); const char * const username = pws ? pws->pw_name : "default"; #endif m_username = username; /** Get appdata path **/ #ifdef _WINDOWS char appdata_path[MAX_PATH]; if(SHGetFolderPath(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0, SHGFP_TYPE_CURRENT, appdata_path) != S_OK) throw File_Ops_Init_Failure(); #else const char * const appdata_path = pws ? pws->pw_dir : "/tmp/"; #endif m_appdata_path = appdata_path; /** Ensure g_unique_app_identifier is set **/ String &unique_app_identifier = get_unique_app_identifier(); if(unique_app_identifier.empty()) unique_app_identifier = "zenilib"; }
bool redirect_cout (const std::string& fn) { static std::ofstream alt_cout; alt_cout.open (fn.c_str(), std::ios::out | std::ios::binary); if (alt_cout.fail() ) return false; std::cout.rdbuf (alt_cout.rdbuf() ); return true; }
// -------------------------------------------------------------------------- // UnitySetInterfaces void UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces *unityInterfaces) { #if defined(ENABLE_LOGGING) && defined(ENABLE_LOGFILE) s_debugLogFile.open("RenderPluginLog.txt"); // Capture std::cout and std::cerr from RenderManager. if (s_debugLogFile) { s_oldCout = std::cout.rdbuf(); std::cout.rdbuf(s_debugLogFile.rdbuf()); s_oldCerr = std::cerr.rdbuf(); std::cerr.rdbuf(s_debugLogFile.rdbuf()); } #endif // defined(ENABLE_LOGGING) && defined(ENABLE_LOGFILE) s_UnityInterfaces = unityInterfaces; s_Graphics = s_UnityInterfaces->Get<IUnityGraphics>(); s_Graphics->RegisterDeviceEventCallback(OnGraphicsDeviceEvent); // Run OnGraphicsDeviceEvent(initialize) manually on plugin load OnGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize); }
void openStreamInto( Ptr<Config> const& config, std::ofstream& ofs ) { // Open output file, if specified if( !config->getFilename().empty() ) { ofs.open( config->getFilename().c_str() ); if( ofs.fail() ) { std::ostringstream oss; oss << "Unable to open file: '" << config->getFilename() << "'"; throw std::domain_error( oss.str() ); } config->setStreamBuf( ofs.rdbuf() ); } }
bool setup_files() { configOptions["login_logfile"] = configOptions["logdir"] + configOptions["starttime"] + std::string(".log"); configOptions["kill_logfile"] = configOptions["logdir"] + configOptions["starttime"] + std::string(".kills"); configOptions["cout_logfile"] = configOptions["coutdir"] + configOptions["starttime"] + std::string(".out"); configOptions["cerr_logfile"] = configOptions["coutdir"] + configOptions["starttime"] + std::string(".err"); std::cout << "redirecting all further output to file: " << configOptions["cout_logfile"] << std::endl; std::cout << "redirecting error output to file: " << configOptions["cerr_logfile"] << std::endl; // open files for redirectings stdout/stderr coutfile.open(configOptions["cout_logfile"].c_str(), std::ios::out | std::ios::trunc); cerrfile.open(configOptions["cerr_logfile"].c_str(), std::ios::out | std::ios::trunc); // check if files are ok if (!coutfile.good()) { std::cerr << "Could not open stdout log file for writing: " << configOptions["cout_logfile"] << std::endl; return false; } if (!cerrfile.good()) { std::cerr << "Could not open stderr log file for writing: " << configOptions["cerr_logfile"] << std::endl; return false; } // redirect stdout/stderr std::cout.rdbuf(coutfile.rdbuf()); std::cerr.rdbuf(cerrfile.rdbuf()); kill_log.open(configOptions["kill_logfile"].c_str()); if (!kill_log.good()) { std::cerr << "Could not open kill log file for writing: " << configOptions["kill_logfile"] << std::endl; return false; } return true; }
IO::IO(const Settings &s, MPI_Comm comm) { m_outputfilename = s.outputfile; if (m_outputfilename == "cout") { buf = std::cout.rdbuf(); } else { int rank; MPI_Comm_rank(comm, &rank); std::string rs = std::to_string(rank); of.open(m_outputfilename + rs + ".txt"); buf = of.rdbuf(); } }
void setTrace(Rose_STL_Container<string> &cmdLineArgs) { if ((CommandlineProcessing::isOption (cmdLineArgs,"--verbose","",true)) || (CommandlineProcessing::isOption (cmdLineArgs,"-v","",true)) ) { tracePtr = &std::cout; verbose = true; } else { static std::ofstream null("/dev/null"); static std::ostream nullTrace(null.rdbuf()); nullPtr = &null; tracePtr = &nullTrace; verbose = false; } }
void mpi_spread::redirectOut() { #ifdef HAVE_MPI if (rank != 0) { std::streambuf *psbuf; dev_null.open("/dev/null"); backup_out = std::cout.rdbuf(); // back up cout's streambuf backup_err = std::cout.rdbuf(); // back up cout's streambuf psbuf = dev_null.rdbuf(); // get file's streambuf std::cout.rdbuf(psbuf); // assign streambuf to cout std::cerr.rdbuf(psbuf); // assign streambuf to cout } #endif }
bool TraceLog::activateTraceLog( bool isActive ){ if ( isActive ){ try{ std::string traceFileName = "traceLog"+getTime()+".log"; out.open(traceFileName.c_str() ); std::streambuf *countbuf = std::cout.rdbuf(); std::cout.rdbuf ( out.rdbuf() ) ; AddTimeStamp ats( cout ); std::cout<<"buffer pointed\n"; } catch ( std::exception &e ){ std::cerr<<"exception caight\n"; return false; } return true; } else{ //have to do some logic thus std::cout<<"print data\n" won;t print any thing to standard output. } }
int main(int argc,char *argv[]) { typedef PsimagLite::Concurrency ConcurrencyType; ConcurrencyType concurrency(&argc,&argv,1); InputCheck inputCheck; PsimagLite::String filename=""; int opt = 0; OperatorOptions options; PsimagLite::String strUsage(argv[0]); if (utils::basename(strUsage) == "operator") options.enabled = true; strUsage += " -f filename [-k] [-p precision] [-V] [whatToMeasure]"; int precision = 6; bool keepFiles = false; bool versionOnly = false; /* PSIDOC DmrgDriver \begin{itemize} \item[-f] {[}Mandatory, String{]} Input to use. \item[-p] [Optional, Integer] Digits of precision for printing. \item[whatToMeasure] {[}Optional, String{]} What to measure in-situ \item[-l] {[}Optional, String{]} Without this option std::cout is redirected to a file. This option with the string ``?'' prints name of such log file. This option with the string ``-'' writes std::cout to terminal. In other cases, string is the name of the file to redirect std::cout to. \item[-k] [Optional] Keep untar files \end{itemize} */ /* PSIDOC OperatorDriver The arguments to the \verb!operator! executable are as follows. \begin{itemize} \item[-f] [Mandatory, String] Input to use. The Model= line is very important in input.inp. \item[-s] [Optional, Integer] Site for operator. Meaningful only for Models where the Hilbert space depends on the site (different kinds of atoms). Defaults to 0. \item[-l] [Mandatory, String] The label or name for this operator. This is model dependent. For example to obtain $c_{\uparrow}$ for the Hubbard model, say \begin{verbatim} ./operator -l c -f input.inp\end{verbatim} See the function naturalOperator for each Model. \item[-d] [Optional, Integer] Degree of freedom (spin, orbital or combination of both) to use. This is model dependent. For example to obtain $c_\downarrow$ for the Hubbard model, say \begin{verbatim}./operator -l c -d 1 -f input.inp\end{verbatim} See the function naturalOperator for each Model. Defaults to 0. \item[-t] [Optional, Void] Transpose the operator. For example to obtain $c^\dagger_\uparrow$ for a Hubbard model, say \begin{verbatim}./operator -l c -t -f input.inp\end{verbatim} \end{itemize} */ while ((opt = getopt(argc, argv,"f:s:l:d:F:o:p:tkV")) != -1) { switch (opt) { case 'f': filename = optarg; break; case 'o': std::cerr<<argv[0]<<": Omit the \"-o\". It's not needed anymore.\n"; std::cerr<<"\t Write the insitu measurements at the end of the command line\n"; return 1; case 's': options.site = atoi(optarg); break; case 'l': options.label = optarg; break; case 'd': options.dof = atoi(optarg); break; case 't': options.transpose = true; break; case 'k': keepFiles = true; break; case 'F': std::cerr<<argv[0]<<": Omit the \"-F\". It's not needed anymore.\n"; std::cerr<<"\t It is implied by the label: n=bosonic, c=fermionic, etc\n"; return 2; case 'p': precision = atoi(optarg); std::cout.precision(precision); std::cerr.precision(precision); break; case 'V': versionOnly = true; options.label = "-"; break; default: inputCheck.usageMain(strUsage); return 1; } } // sanity checks here if (filename=="" && !versionOnly) { inputCheck.usageMain(strUsage); return 1; } PsimagLite::String insitu = (optind < argc) ? argv[optind] : ""; if (!options.enabled && options.label != "-") { bool queryOnly = (options.label == "?"); if (options.label == "" || options.label == "?") { options.label = ArchiveFilesType::coutName(filename); if (queryOnly) { std::cout<<options.label<<"\n"; return 0; } } GlobalCoutStream.open(options.label.c_str()); if (!GlobalCoutStream || GlobalCoutStream.bad() || !GlobalCoutStream.good()) { PsimagLite::String str(argv[0]); str += ": Could not redirect std::cout to " + options.label + "\n"; throw PsimagLite::RuntimeError(str); } std::cerr<<argv[0]<<" ATTENTION: All standard output now sent to "; std::cerr<<options.label<<"\n"; std::cerr.flush(); GlobalCoutBuffer = std::cout.rdbuf(); //save old buf std::cout.rdbuf(GlobalCoutStream.rdbuf()); //redirect std::cout to file atexit(restoreCoutBuffer); } // print license if (ConcurrencyType::root() && !options.enabled) { std::cout<<ProgramGlobals::license; Provenance provenance; std::cout<<provenance; } if (versionOnly) return 0; InputNgType::Writeable ioWriteable(filename,inputCheck); InputNgType::Readable io(ioWriteable); ParametersDmrgSolverType dmrgSolverParams(io, false); ArchiveFilesType af(dmrgSolverParams,filename,options.enabled,options.label); if (insitu!="") dmrgSolverParams.insitu = insitu; if (dmrgSolverParams.options.find("minimizeDisk") != PsimagLite::String::npos) dmrgSolverParams.options += ",noSaveWft,noSaveStacks,noSaveData"; #ifndef USE_PTHREADS inputCheck.checkForThreads(dmrgSolverParams.nthreads); #endif ConcurrencyType::npthreads = dmrgSolverParams.nthreads; registerSignals(); PsimagLite::String targeting = inputCheck.getTargeting(dmrgSolverParams.options); bool isComplex = (dmrgSolverParams.options.find("useComplex") != PsimagLite::String::npos); if (targeting=="TimeStepTargetting") isComplex = true; if (isComplex) { mainLoop0<MySparseMatrixComplex, CvectorSizeType>(io,dmrgSolverParams,targeting,options); } else { mainLoop0<MySparseMatrixReal, CvectorSizeType>(io,dmrgSolverParams,targeting,options); } if (options.enabled) return 0; af.deletePackedFiles(); if (!keepFiles) ArchiveFilesType::staticDelete(); }
/* Random stuff */ u16 g_selected_material = 0; /* Debug streams - use these to disable or enable outputs of parts of the program */ std::ofstream dfile("debug.txt"); //std::ofstream dfile2("debug2.txt"); // Connection //std::ostream dout_con(std::cout.rdbuf()); std::ostream dout_con(dfile.rdbuf()); // Server //std::ostream dout_server(std::cout.rdbuf()); std::ostream dout_server(dfile.rdbuf()); // Client //std::ostream dout_client(std::cout.rdbuf()); std::ostream dout_client(dfile.rdbuf()); /* TimeTaker */ class TimeTaker {
int main() { char buffer[64]; //logStream.rdbuf()->pubsetbuf(buffer, sizeof(buffer)); logStream.rdbuf()->pubsetbuf(nullptr, 0); logStream.open("log.txt"); //try { ny::logLogger().stream = &logStream; ny::warningLogger().stream = &logStream; ny::errorLogger().stream = &logStream; ny::sendLog("Started Iro Desktop"); iro::Compositor myCompositor; iro::Seat mySeat(myCompositor); iro::ForkHandler myForkHandler(myCompositor); std::unique_ptr<iro::DBusHandler> myDBusHandler = nullptr; std::unique_ptr<iro::LogindHandler> myLogindHandler = nullptr; std::unique_ptr<iro::DeviceHandler> myDeviceHandler = nullptr; std::unique_ptr<iro::Backend> myBackend = nullptr; std::unique_ptr<iro::TerminalHandler> myTerminalHandler = nullptr; std::unique_ptr<iro::UDevHandler> myUDevHandler = nullptr; std::unique_ptr<iro::InputHandler> myInputHandler = nullptr; if(iro::X11Backend::available()) { iro::X11Backend* xbcknd = new iro::X11Backend(myCompositor, mySeat); myBackend.reset(xbcknd); xbcknd->createOutput(); } else { myDBusHandler.reset(new iro::DBusHandler(myCompositor)); myLogindHandler.reset(new iro::LogindHandler(*myDBusHandler)); myDeviceHandler.reset(new iro::DeviceHandler(*myDBusHandler, *myLogindHandler)); myTerminalHandler.reset(new iro::TerminalHandler(myCompositor)); myBackend.reset(new iro::KmsBackend(myCompositor, *myDeviceHandler)); myUDevHandler.reset(new iro::UDevHandler(myCompositor)); myInputHandler.reset(new iro::InputHandler(myCompositor, mySeat, *myUDevHandler, *myDeviceHandler)); static_cast<iro::KmsBackend*>(myBackend.get())->setCallbacks(*myTerminalHandler); myLogindHandler->onActive([&](bool b) { ny::sendLog("active: ", b); if(b) { myInputHandler->resume(); //myTerminalHandler->activate(myTerminalHandler->number()); //myTerminalHandler->waitActive(myTerminalHandler->number()); } else { myInputHandler->suspend(); } }); std::cout << (int)mySeat.keyboard()->modifiers() << "\n"; std::cout << (int)(iro::Keyboard::Modifier::ctrl | iro::Keyboard::Modifier::alt) << "\n"; if(mySeat.keyboard()) { mySeat.keyboard()->onKey([&](unsigned int key, bool pressed) { if(!pressed) return; if(mySeat.keyboard()->modifiers() != (iro::Keyboard::Modifier::ctrl | iro::Keyboard::Modifier::alt)) return; if(key == KEY_Q) { idleSwitchSource = wl_event_loop_add_idle(&myCompositor.wlEventLoop(), idleSwitch, myTerminalHandler.get()); vtSwitchTo = myTerminalHandler->number() - 1; } else if(key == KEY_E) { idleSwitchSource = wl_event_loop_add_idle(&myCompositor.wlEventLoop(), idleSwitch, myTerminalHandler.get()); vtSwitchTo = myTerminalHandler->number() + 1; } }); } } if(mySeat.keyboard()) { mySeat.keyboard()->onKey([&](unsigned int key, bool pressed) { if(mySeat.keyboard()->modifiers() != iro::Keyboard::Modifier::alt) return; if(pressed && key == KEY_T) { ny::sendLog("starting weston terminal"); myForkHandler.exec("weston-terminal", {"--shell=/bin/bash"}); } }); } ny::sendLog("finished backend setup"); ny::sendLog("set up x window manager"); if(!myBackend) { ny::sendError("no valid backend found"); return 0; } myCompositor.backend(*myBackend); auto* myShell = loadShell("libiro-shell.so"); if(!myShell) { ny::sendError("failed to load shell module"); return 0; } myShell->init(myCompositor, mySeat); myCompositor.shell(*myShell); for(auto* outp : myBackend->outputs()) outp->onDraw(nytl::memberCallback(&iro::ShellModule::render, myShell)); auto xwm = std::make_unique<iro::XWindowManager>(myCompositor, mySeat); ny::sendLog("starting main loop"); myCompositor.run(nytl::seconds(60)); //myCompositor.run(); ny::sendLog("Finished Iro Desktop"); *ny::logLogger().stream << std::flush; } //catch(const std::exception& err) //{ // ny::sendLog("Caught Exception: ", err.what()); //} *ny::logLogger().stream << "iro main extited normally. " << std::flush; return 1; }
RAIIcout_redirect(std::ofstream& os): _oldbuf(std::cout.rdbuf()) { std::cout.rdbuf(os.rdbuf()); }