Inicio > Programación > c++ : Imprimir a fichero o salida estándar de forma genérica

c++ : Imprimir a fichero o salida estándar de forma genérica

Miércoles, 17 de marzo de 2010 Dejar un comentario Ir a comentarios

Cuando queremos mostrar datos al usuario en nuestros programas normalmente tenemos que elegir entre mostrarlos por la salida estandar o a un fichero. En C++ se suele utilizar la clase std::cout para hacer referencia a la salida estandar y std::ofstream para manejar flujos de salida. No obtante, podemos utilizar la clase std::streambuf para referenciar a los búferes de las clases anteriores y así poder trabajar en nuestros programas de forma genérica.

Simplemente introduciendo el siguiente bloque de código, podemos hacer que la salida de datos se redirija a un fichero o a la salida de pantalla estandar según si se especifica un fichero de salida o no.

		std::streambuf *buf;
		std::ofstream of;
		if(!outputPath.empty()) {
			of.open(outputPath.c_str());
			if (!of.is_open())
			{
				std::cerr << "El fichero de salida no se pudo abrir para escribir";
				exit (-1);
			}
			buf = of.rdbuf();
		} else
			buf = std::cout.rdbuf();
		std::ostream out(buf);

When you want to show data to users in your programs, you usually have to choose between to display these in the standar output or to write them in a file. In C++, std::cout refers to the standar output while std::ofstream is commonly used for handle output streams. Nevertheless, you can use std::streambuf to refer to the buffers of the previous classes and, therefore, handle your outputs in a generic way.

With the following block of code, the output data is redirected to a file or to the standard output depending on whether you indicate an output file.

		std::streambuf *buf;
		std::ofstream of;
		if(!outputPath.empty()) {
			of.open(outputPath.c_str());
			if (!of.is_open())
			{
				std::cerr << "Output file could not be opened for writting";
				exit (-1);
			}
			buf = of.rdbuf();
		} else
			buf = std::cout.rdbuf();
		std::ostream out(buf);
GD Star Rating
loading...
c++ : Imprimir a fichero o salida estándar de forma genérica, 9.7 out of 10 based on 3 ratings
Share
  1. tArKi
    Jueves, 18 de marzo de 2010 a las 07:46 | #1
    GD Star Rating
    loading...

    Gracias por el post. ;)

  1. Sin trackbacks aún.