コード例 #1
0
ファイル: FileSystemStorage.cpp プロジェクト: binary42/OCI
bool File::write(std::ofstream& stream)
{
  CwdGuard cg(physical_dir_);
  stream.open(ACE_TEXT_ALWAYS_CHAR(physical_file_.c_str()),
              ios::binary | ios::out);
  return !stream.bad() && !stream.fail();
}
コード例 #2
0
ファイル: Log.cpp プロジェクト: Hybris95/LolSceneSwitch
void LogLastError()
{
	if (!ofs.bad())
	{
		DWORD eNum = GetLastError();
		TCHAR sysMsg[256];
		if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, eNum,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), sysMsg, 256, NULL) == 0)
		{
			Log("ERROR | LogLastError | Couldn't format error message with number", eNum, true);
			return;
		}

		// find end of string
		TCHAR *p = sysMsg;
		while ((*p > 31) || (*p == 9))
		{
			++p;
		}

		// remove unused end
		do
		{
			*p-- = 0;
		} while ((p >= sysMsg) && ((*p == '.') || (*p < 33)));

		Log("      | GetLastError |", sysMsg);
	}
}
コード例 #3
0
ファイル: Log.cpp プロジェクト: Hybris95/LolSceneSwitch
void Log(_In_ char const * text)
{
	if (!ofs.bad())
	{
		ofs << text << std::endl;
	}
}
コード例 #4
0
/* Writes the grid of values of an EM map to a MRC file */
void MRCReaderWriter::write_data(std::ofstream &s,const float *pt)
{

  s.write((char *)pt,sizeof(float)*header.nx * header.ny * header.nz);
  IMP_USAGE_CHECK(!s.bad(),
            "MRCReaderWriter::write_data >> Error writing MRC data.");
  IMP_LOG(TERSE,"MRC file written: grid " << header.nx << "x" << header.ny
          << "x" << header.nz << std::endl);
}
コード例 #5
0
ファイル: CGnuplot.cpp プロジェクト: ldsc/lib_ldsc
//----------------------------------------------------------------------------------
// Opens a temporary file
std::string Gnuplot::create_tmpfile(std::ofstream &tmp)
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
    char name[] = "gnuplotiXXXXXX"; //tmp file in working directory
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    char name[] = "/tmp/gnuplotiXXXXXX"; // tmp file in /tmp
#endif

    // check if maximum number of temporary files reached
    if (Gnuplot::tmpfile_num == GP_MAX_TMP_FILES - 1)
    {
        std::ostringstream except;
        except << "Maximum number of temporary files reached (" << GP_MAX_TMP_FILES
               << "): cannot open more files" << std::endl;

        throw GnuplotException( except.str() );
        return "";
    }

    // int mkstemp(char *name);
    // shall replace the contents of the string pointed to by "name" by a unique filename,
    // and return a file descriptor for the file open for reading and writing.
    // Otherwise, -1 shall be returned if no suitable file could be created.
    // The string in template should look like a filename with six trailing 'X' s;
    // mkstemp() replaces each 'X' with a character from the portable filename character set.
    // The characters are chosen such that the resulting name does not duplicate the name of an existing file at the time of a call to mkstemp()


    // open temporary files for output
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
		if (_mktemp(name) == nullptr)
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    if (mkstemp(name) == -1)
#endif
    {
        std::ostringstream except;
        except << "Cannot create temporary file \"" << name << "\"";
        throw GnuplotException(except.str());
        return "";
    }

    tmp.open(name);
    if (tmp.bad())
    {
        std::ostringstream except;
        except << "Cannot create temporary file \"" << name << "\"";
        throw GnuplotException(except.str());
        return "";
    }

    // Save the temporary filename
    this->tmpfile_list.push_back(name);
    Gnuplot::tmpfile_num++;

    return name;
}
コード例 #6
0
ファイル: io.hpp プロジェクト: cpumul4/cpuex
template <class T> inline void exec_output(T reg, int which_byte){
  union {
    char byte[4];
    T word;
  } tmp;

  tmp.word = reg;
  fout.write(tmp.byte + which_byte, 1);
  if( fout.bad() ) {
    throw (std::string)"fatal Error:データ読み込みエラー";
  }
  return;
}
コード例 #7
0
ファイル: plot.cpp プロジェクト: ashang/pepper
// Creates a temporary file
std::string Plot::tempfile(std::ofstream &out)
{
	std::string path;
	sys::fs::mkstemp(&path);

	out.open(path.c_str());
	if (out.bad()) {
		throw PEX(str::printf("Unable to open temporary file '%s'", path.c_str()));
	}

	m_tempfiles.push_back(path);
	return path;
}
コード例 #8
0
ファイル: Log.cpp プロジェクト: Hybris95/LolSceneSwitch
void Log(_In_ char const * text, _In_opt_ char const * value)
{
	if (!ofs.bad())
	{
		if (value != nullptr)
		{
			ofs << text << " '" << value << "'" << std::endl;
		}
		else
		{
			ofs << text << " 'NULL'" << std::endl;
		}
	}
}
コード例 #9
0
ファイル: Log.cpp プロジェクト: Hybris95/LolSceneSwitch
void Log(_In_ char const * text, long long value, bool hex)
{
	if (hex)
	{
		if (!ofs.bad())
		{
			std::stringstream stream;
			stream << std::hex << value;
			ofs << text << " '" << stream.str() << "'" << std::endl;
		}
	}
	else
	{
		ofs << text << " '" << value << "'" << std::endl;
	}
}
コード例 #10
0
ファイル: compactIntArray.cpp プロジェクト: bluecliff/CSA
bool compactIntArray::write(std::ofstream& fout)
{
    fout.write((char*)&size, sizeof(size));
    fout.write((char*)&wordsize, sizeof(wordsize));
    fout.write((char*)&innersize, sizeof(innersize));

    fout.write((char*)array, sizeof(*array) * innersize);
    if(fout.bad())
    {
        return false;
    }
    else
    {
        return true;
    }
}
コード例 #11
0
ファイル: Log.cpp プロジェクト: Hybris95/LolSceneSwitch
void Log(_In_ char const * text, _In_opt_ WCHAR const * value)
{
	if (!ofs.bad())
	{
		if (value != nullptr)
		{
			size_t length;
			char converted[256];
			wcstombs_s(&length, converted, value, 256);
			ofs << text << " '" << converted << "'" << std::endl;
		}
		else
		{
			ofs << text << " 'NULL'" << std::endl;
		}
	}
}
コード例 #12
0
void inicializarSharedObjects(CajaRegistradora& caja, Grilla& grilla, GrillaJefe& grillaJefe, Surtidores& surtidores,
		unsigned int cantEmpleados, unsigned int cantSurtidores,
		std::ofstream& archivoColaInputJefe, ColaConPrioridad<automovil>& colaAutosJefe) {
	caja.inicializarCaja();
	grilla.inicializarGrilla(cantEmpleados);
	grillaJefe.inicializarGrillaJefe();
	surtidores.inicializarSurtidores(cantSurtidores);

	if (archivoColaInputJefe.fail() || archivoColaInputJefe.bad()) {
		std::string me = __FILE__ ":inicializarSharedObjects";
		std::string _msg = std::string("Error creando archivo para la cola entre el jefe y el input: ") + std::string(strerror(errno));
		Logger::error(_msg, me);
		throw _msg;
	}
	// TODO: Ordenar la creacion de esta cola. Encapsularlo porque queda feito
	colaAutosJefe = ColaConPrioridad<automovil> ( colaInputJefe, colaInputJefeKey );

}
コード例 #13
0
void MRCReaderWriter::write_header(std::ofstream &s)
{
  header.ispg = 1065353216;
  memcpy(header.map, "MAP ", 4);
  //  header.machinestamp = get_machine_stamp();
  int wordsize=4;
  s.write((char *) &header.nx,wordsize);
  s.write((char *) &header.ny,wordsize);
  s.write((char *) &header.nz,wordsize);
  s.write((char *) &header.mode,wordsize);
  s.write((char *) &header.nxstart,wordsize);
  s.write((char *) &header.nystart,wordsize);
  s.write((char *) &header.nzstart,wordsize);
  s.write((char *) &header.mx,wordsize);
  s.write((char *) &header.my,wordsize);
  s.write((char *) &header.mz,wordsize);
  s.write((char *) &header.xlen,wordsize);
  s.write((char *) &header.ylen,wordsize);
  s.write((char *) &header.zlen,wordsize);
  s.write((char *) &header.alpha,wordsize);
  s.write((char *) &header.beta,wordsize);
  s.write((char *) &header.gamma,wordsize);
  s.write((char *) &header.mapc,wordsize);
  s.write((char *) &header.mapr,wordsize);
  s.write((char *) &header.maps,wordsize);
  s.write((char *) &header.dmin,wordsize);
  s.write((char *) &header.dmax,wordsize);
  s.write((char *) &header.dmean,wordsize);
  s.write((char *) &header.ispg,wordsize);
  s.write((char *) &header.nsymbt,wordsize);
  s.write((char *) &header.user,wordsize*IMP_MRC_USER);
  s.write((char *) &header.xorigin,wordsize);
  s.write((char *) &header.yorigin,wordsize);
  s.write((char *) &header.zorigin,wordsize);
  s.write((char *) &header.map,wordsize);
  s.write((char *) &header.machinestamp,wordsize);
  s.write((char *) &header.rms,wordsize);
  s.write((char *) &header.nlabl,wordsize);
  s.write((char *) &header.labels,
          sizeof(char)*IMP_MRC_NUM_LABELS*IMP_MRC_LABEL_SIZE);
  IMP_USAGE_CHECK(!s.bad(),
            "MRCReaderWriter::write_header >> Error writing MRC header");
}
コード例 #14
0
ファイル: streamFuns.cpp プロジェクト: kellyquek/STAR
void fstreamWriteBig(std::ofstream &S, char* A, unsigned long long N, std::string fileName, std::string errorID, Parameters *P) {

    struct statvfs statvfsBuf;
    statvfs(fileName.c_str(), &statvfsBuf);
    P->inOut->logMain << "Writing " << N << " bytes into " <<fileName << " ; empty space on disk = " << statvfsBuf.f_bavail * statvfsBuf.f_bsize <<" bytes ..." <<flush;
    
    unsigned long long C=0;
    unsigned long long iC;
    for (iC=0; iC<N/fstream_Chunk_Max; iC++) {
        S.write(A+C,fstream_Chunk_Max);
        C+=fstream_Chunk_Max;
    };
    if (!S.fail()) S.write(A+C,N%fstream_Chunk_Max);
    if (S.fail()) {//failed to write

        struct statvfs statvfsBuf;
        statvfs(fileName.c_str(), &statvfsBuf);
    
//         system(( "ls -lL "+ P->genomeDir + " > "+ P->genomeDir +"/error.info 2>&1").c_str());
//         ifstream error_info((P->genomeDir +"/error.info").c_str());
//         P->inOut->logMain <<error_info.rdbuf();
        
        struct stat statBuf;
        stat(fileName.c_str(), &statBuf);
        
        remove(fileName.c_str());
        
        ostringstream errOut;
        errOut << errorID<<": exiting because of *OUTPUT FILE* error: could not write the output file "<< fileName <<"\n";
        errOut << "fail()=" <<S.fail() <<" ; bad()="<< S.bad()<<"\n";
        errOut << "Error while trying to write chunk # " << iC << "; "<< C << " bytes\n";
        errOut << "File size full = "<< N <<" bytes\n";        
        errOut << "File size on disk = " << statBuf.st_size<<" bytes\n";
        errOut << "Solution: check that you have enough space on the disk\n";
        errOut << "Empty space on disk = " << statvfsBuf.f_bavail * statvfsBuf.f_bsize <<" bytes\n";
        exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_FILE_WRITE, *P);
    };
    P->inOut->logMain << " done\n" <<flush;
};
コード例 #15
0
ファイル: mesh_io_vtk.cpp プロジェクト: fredroy/sofa
 virtual bool write(std::ofstream& out, int n, int groups, bool binary)
 {
     if (n > dataSize && !data) return false;
     if (binary)
     {
         out.write((char*)data, n * sizeof(T));
     }
     else
     {
         if (groups <= 0 || groups > n) groups = n;
         for (int i = 0; i < n; ++i)
         {
             if ((i % groups) > 0)
                 out << ' ';
             out << data[i];
             if ((i % groups) == groups-1)
                 out << '\n';
         }
     }
     if (out.bad())
         return false;
     return true;
 }
コード例 #16
0
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();
}