What are 'aliased' stream buffers? - c++

What are 'aliased stream buffers`? I encountered the term in a comment on an answer of mine.

I've never heard the term before, but in the thread you cite,
the person who used it also gave an example: two streams which
use the same streambuf.
Of course, just because two streams don't use the same
streambuf, doesn't mean that data written to them doesn't
ultimately end up in the same place; that they don't alias the
same sink, if that is what is meant. There are filtering
streambuf's, which forward the actual sinking and sourcing to
another streambuf, and on most systems, it's possible to open
a file at the system level, and connect a streambuf (or two) to
it.
--
James Kanze

It means an object with different name, for example this:
ostream &lbw = cout;
lbw << "Shahid out" << "Sachin in" << endl; //goes to cout!

What probably was meant in the comment there is this:
ofstream file;
file.rdbuf(cout.rdbuf());
// writes to cout
file << "hello";
So now the check there doesn't work:
if(&file == &cout)
// no, it doesn't

Related

What exactly are cout/cin?

I know Java and now want to learn C++. I can't understand what are cout (character output stream) and cin (character input). Are these global variables? Then why
"My message">>cout;
doesn't work? But
cout<<"My message";
works.
cout is an instance of the class std::ostream, and yes, it's a global variable. But operator>>(char *, ostream& os); hasn't been declared by the relevant header, so "My message">>cout; will give an error of something like "can't find an operator >> which takes arguments const char * and std::ostream" (and possibly a lot more errors because sometimes compilers get very confused by these sort of things).
cin is the same thing, except std::istream
If you really want to mess with peoples heads, you could do:
template<typename T>
std::ostream& operator>>(T x, std::ostream& os)
{
os << x;
return os;
}
Of course, it won't work for "My Message " >> "Some other string" >> cout;, which is probably one of the reasons it's not done that way.
Note that this is simply slight abuse of the operator overloading, where we have a custom type as the left-hand side, and standard or non-standard type on the right hand side. cout is no different from some other variable of a custom type.
std::cout and std::cin are indeed global variables. Your code doesn't compile because that's not the way the language works. You have to put the stream on the left, and then the operator and then the variables you are streaming into/out of. (For output, you can use literals and expressions as well as variables.)
consider the arrows as streams. << stands for output stream , while >> stands for input stream.
so cout << "hello" means output to screen
when cin >> a means asks from a user input for variable a
cout can also use "+" like for example you can add more strings to one stream like this
cout << "Hello" << "world" << "I am john";
cin in the same way can ask for input from multiple variables
cin >> a >> b ; will ask from user to input two times one for each variable
iostream is a header file which contain classes handling input and output operations for a console. Its like you create a object when you say "cin" for the input class handling input operation for a console in the header file. Same can be said about "cout" where a object is being created from a class handling output operation to a console in the header file.
When you consider "cin", imagine creating a pipe connected to the console and your program and an object "cin" taking your inputs from the console which you provide through your keyboard and dumping them on to the program. That's the reason you can see having a ">>" operator for cin and you can find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cin".
Whereas for "cout", imagine creating a pipe connected to the console and your program and an object "cout" taking its input from the program and dumping them on to the console. That's the reason you can see having a "<<" operator for cout and you find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cout".
So basically you need to first specify what object you would be creating for your operations and then assigning an operator to accomplish your task. If you include the header file, then its like you could use those objects anywhere throughout your program.
So, "My message">>cout; doesn't function the way you expect it to be because there is no object and an operator to accomplish your task whereas cout<<"My message"; does.
The technical aspects have been described by Mats Petersson. This is just to give you a general picture of what's actually happening pictorially. Hope this helps you.

C++ How to write a logfile

I have to write a program for school that calculates current, voltage, and efficiency. I have almost finished the program but now I want to write the results in a logfile. I have already read some threads but it didn't really help.
here is the part that I want to write in a logfile:
cout<<"Die spannung U1 betraegt"<<U1<<"Ohm."<<endl;
I would really appreciate help thanks.
Simply using File I/O in C++ locally should solve your issue:
#include <fstream>
//...
ofstream fout("logfile.txt");
if (fout){
fout << "Die spannung U1 betraegt" << U1 << "Ohm." <<endl;
fout.close();
}
However, logging can become very cumbersome, so people have come up with all kinds of solutions for loggers. I found this article on logfiles (In context of the Singleton design pattern) to be very useful.
I would recommend using FILE and fprintf.
http://pic.dhe.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtpc2%2Fcpp_fprintf-printf-sprintf.html
Remember - if you have threads - you need to protect the object,
don't forget to fflush() when the content is meaningful, and to fclose when you're done.
There are other methods to do it- I presonally like the bare bone the most..

can I modify ofstream before writting to disk?

std::ofstream ofs;
ofs << "Hello, world!" << endl;
Now I want to modify the contents of ofs to "Hello, money!" before writting to disk?
How can I implement it?
The std::endl IO manipulator will flush the content of the stream buffer, so you will have to change it into a '\n' if you later want to process the stream before its content gets flushed.
Also, under the assumption that the reason you actually want to do this is because you need to manipulate the string which is going to be written after formatting, I shall make you aware of the fact that you can use an std::ostringstream to exploit the functionality of formatted streaming and gather the result into a string, which you can then manipulate and normally write to a file.
If this was obvious information for you and your use case is more complex, then you will have to write your own stream buffer, as pointed out by #MatsPetersson.
Edit: You should make a class derived from filebuf (for the purpose of this discussion myfilebuf and use that to construct an ostream, which is more accurate than the above.
In the myfilebuf you implement sputbackc, and have a statemachine to identify "Hello, World!", and replace it with "Hello, Money!", which probably means buffering a second layer until you know which it is.

Convert from C++ style printing to my_printf()

C++ purists may want to look away now. You will hate this.
I have been given an open source windows console app that I am merging with a pre-existing, very old, very large windows app of my own. My old program started life as pure C though recently has been tweaked so that it can compile as C++. My program makes extensive use of a my_printf() function which prints text to a window.
The old console app does its printing C++ style via streams (I have never used this type of printing mechanism before).
When converting the console app to work under my system I could manually edit all the lines that do printing so that they use my_printf() instead. But before I embarked on that I thought I'd just check with StackOverflow to see if I was missing a trick. For example I could imagine somehow letting the C++ prints be done via the stream and then somehow scooping the final text somewhere and then calling my_printf() with the result. Might that be possible?
EDIT: please note my knowledge of C++ is extremely limited and I may need to look some things up in order to understand your answers so please use language that facilitates this.
There's indeed a trivial trick. But C++ impurists will hate the fact that C++ has a pure solution ;)
std::ostream is responsible for formatting, but not printing itself. That's handled by std::streambuf. std::cout combines a std::ostream formatter with a std::streambuf-derived object that writes to stdout.
However, you can change the streambuf backing an ostream with ostream::rdbuf(newbuf). As std::cout is just another ostream, you can replace its streambuf too. In this case, you only need to come up with a streambuf-derived class that writes already-formatted output to my_printf(). That should be quite trivial.
You might find string streams useful. For example:
std::ostringstream os;
os << "Print " << whatever << data;
my_printf( "%s", os.str().c_str() );
In case you were feeling adventurous, you could write your own streambuf instead that used my_printf underneath, and inject it into the stream object that is currently used in output statements (e.g. std::cout). Be warned that this latter approach might not be trivial, however it would result in almost no changes to existing codebase.
Subclass std::ostream and make operator << call my_print_f(). You can use internal stringstream in your stream to retrieve string representation of operator << arguments.
Then you'd just have to do find&replace, replacing cout (or whatever stream you directed your output to in the console app) with an instance of your stream class.
Something along these lines might be helpful:
http://www.codeproject.com/KB/debug/debugout.aspx
Should be obvious where the meat of it is, so you can make it print via your own systems, or what have you. In theory, you'd need only search for references to std::cout and replace them with references to your own object.
Overloading the global operator<< is probably what will solve your problem:
#include <iostream>
#include <cstdio>
static int
my_printf (const char* s)
{
printf ("my_printf: %s\n", s);
}
namespace std {
std::ostream& operator<< (std::ostream& out, const char* s)
{
my_printf (s);
return out;
}
}
int
main ()
{
std::cout << "hello, world"; // => my_printf: hello, world
return 0;
}

Does setbuf() affect cout?

Yet again, my teacher was unable to answer my question. I knew who may be able to...
So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put
setbuf( stdout , NULL );
at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.
My question is this: will this statement affect a cout statement, or simply a printf() statement that I call?
Thanks in advance!
By default, iostreams and stdio are synchronised. Reference.
This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise std::endl or std::flush (from <ostream>), which may help you. e.g.,
std::cout << "Hello, world!" << std::endl;
or
std::cout << "Hello, world!\n" << std::flush;
Both of these do the same thing. (std::endl = print endline, then flush.)
By default, if stdout or cout is printing to a console, the output is line buffered. This means that every newline that is printed will flush the output. You can explicitly call flush() whenever you want to override the behavior just in case say, the output is going to be redirected to a file and you want to use tail -f and need certain outputs in realtime.
As Chris said, sync_with_stdio should tie the unbuffered stdout with an unbuffered cout (by default), but if all you are doing is using cout, instead of using setbuf on stdout, a better option is to use pubsetbuf on the pointer returned by rdbuf. ie:
// make cout unbuffered
std::cout.rdbuf()->pubsetbuf(0, 0);
Another function that may be interesting to look at is tie.
Usually, when it's important to see the output immediately, we're talking about complex highly-reliable financial routine that must log a transaction all the way to hard drive before actually sending it to counterparty. Or, (much more common case) we want to see debug messages even when the program is crashing.
Since you're studying, I'll assume you're dealing with the second case. In that case, my advice would be to use stderr rather than stdout. It is unbuffered by default, and you can redirect it separately from stdout, putting your output in one place and your logging in another.