Can cout be associated with anything other than monitor? - c++

'cout is an output stream object that is attached to the process's standard output device,often to the terminal from which the program is run'-my book says so.Just curious about the following:
Is there any case where cout is made to be attached to any other output devices such as may be printer?Or it is like cout refers to monitor and cin to keyboard all the time.

cin is the standard input, and while most systems get their input from the keyboard it is not necessary. cout is standard output, most systems again have stdout (standard output) set to console. But you can redirect it.
For instance to file:
std::ofstream file;
file.open ("test.txt"); // open file
std::streambuf *orig_out = std::cout.rdbuf(); // save cout
std::streambuf *buf = file.rdbuf(); // get file's streambuf
std::cout.rdbuf(buf); // redirect cout to file
std::cout << "This is written to the file";
std::cout.rdbuf(orig_out); // restore cout's original output
file.close(); // close file

Short answer is "yes". Cout is just an output stream. In unix you can create a pipeline
command1 | command2
Command 1's stdout goes to command 2's stdin - i.e. not monitor and keyboard.
stdout (and thus cout) can also be redirected:
command > some_file_or_device.

Yes.
cin and cout are iostreams, they are standard but they are normal too, i.e. you can close stdin and stdout and reopen some other device as the stdin or out.

Related

Redirecting output to file then back to console in C++

The task is to read input from input.txt and write the output to output.txt.
However on completion of the above tasks, further instructions/output should now be displayed to the console.
Came to know about freopen() in c++ which works fine for the first half of the given task. But unfortunately, I have no idea how to redirect the output back to the console again.
void writeIntoFile(){
freopen("input.txt","r",stdin); // Task 1. Reading from input.txt file
freopen("output.txt","w",stdout); // Task 2. Writing to output.txt file
printf("This sentence is redirected to a file.");
fclose(stdout);
printf("This sentence is redirected to console"); // Task 3. Write further output to console
}
What I expected from fclose() was that it would end up writing into the text file and would hence further write the output into the console, but it doesn't. How can I achieve task 3 as well.
Probably what you are looking for is rdbuf() as mentioned by doomista in the comments.
Here is a way to redirect Output.
#include <iostream>
#include <fstream>
int main()
{
/** backup cout buffer and redirect to out.txt **/
std::ofstream out("out.txt");
auto *coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
std::cout << "This will be redirected to file out.txt" << std::endl;
/** reset cout buffer **/
std::cout.rdbuf(coutbuf);
std::cout << "This will be printed on console" << std::endl;
return 0;
}

How to poll input from Linux /dev/input/eventX

I'm working on a project that requires me to get a touchscreen working on Scientific Linux 6.4 (Linux kernel 2.6.32). Although the kernel does not support the touchscreen fully, I am able to see multi-touch events being generated in the /dev/input/eventX location for the touchscreen when I touch the screen.
I'm trying to write a simple C++ program to read the data from the /dev/input/eventX file and parse it so I can manually deal with the multi-touch events, since that seems the only way I'll get this working.
So I wrote the following program:
std::ifstream input("/dev/input/event10");
if(input.is_open()) {
while(input.good()) {
int header;
input >> header;
cout << std::hex << header << " ";
int data[16] = {};
for(int i = 0; i < 16; i++) {
input >> data[i];
cout << std::hex << data[i] << " ";
}
cout << endl;
}
input.close();
} else cout << "Unable to open event handler for input polling..." << endl;
Now, I don't exactly know if my method of reading and parsing the input itself is correct, but when I use the following command in bash:
sudo cat /dev/input/event10 | hexdump -C
I get the input data in the form of a number of lines beginning with an 8-digit hex value followed by 16 2-digit hex values (bytes).
The problem I'm having though is that I always get the message "Unable to open event handler for input polling..." suggesting an issue with opening the file. At first, I thought maybe that because nothing is in that file until an event is generated, it might not be able to be opened as an ifstream. I also tried running the program as sudo just in case it was a permissions issue and got the same message, so I believe it has to do with how I'm opening the file.
Does anyone know the proper way to open and read from these files?
EDIT: My question is regarding why the file is unable to be opened, not necessarily just how to parse the data. The suggested "duplicate" questions don't provide any helpful information in this regard.
Nevermind... there was a trailing space in my filename (which was detected rather than hard-coded). I added a trim function and now it opens just fine.

c++: how to print new line without carriage return [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to make cout behave as in binary mode?
I am using C++ to print binary data to the stdout and then I redirect it to a file.
(I do not want to write directly to a file).
However, when I try to print the value '0A' I am getting '0D 0A'. (this is what I see when I copy the output to HexEdit).
From what I can figure out, '0A' is the ascii for 'new line' so cout automatically adds the '0D' which is 'carriage return'.
What I want is to print 0A alone. how can I do this?
my code:
unsigned char *buf = new unsigned char[width+1];
for (int x = 0; x < width; x++)
{
buf[x] = (unsigned char) src[x];
}
buf[width] = '\0'
cout<<buf;
I've seen this: Print new line to a text file without carriage return (CR) in windows but it does not seem to help me.
Not sure you really can use cout and the << operator without a massive hack. This is because when using << cout treats all data as text data and will perform appropriate transformations as necessary -- including adding a CR character when printing a newline on a Windows platform.
You will need to use the write method of cout, instead of using the insertion operator <<. The write method will not format your data, but is more awkward to use.
http://www.cplusplus.com/reference/iostream/ostream/write/
You can't control the end of line sequence with any of the standard output streams or files. The only way to deal with this is to freopen() the standard output stdout with an open mode of wb or wb+` to control the underlying formatting, e.g.:
FILE* out = freopen("stdout.txt", "wb", stdout);
std::cout << "hello, world\n";
If you are only using C++ streams you can also replace std::cout's stream buffer with the stream buffer of an appropriately opened std::ofstream, e.g.:
std::ofstream file("stdout.txt", std::ios_base::out);
std::streambuf* coutbuf = std::cout.rdbuf(file.rdbuf());
std::cout << "hello, world\n";
...
std::cout.rdbuf(coutbuf);
You need to restore the original stream buffer to avoid problems with uses of std::cout during destruction: at the very least the stream gets flushed at some point after main() is exited. If you can accept a memory leak, you can use a dynamically allocated std::filebuf directly.
None of the solutions above actually writes the output to the standard output, they all write to a file. I don't know how to reopen the standard output on a Windows system (on a UNIX system you'd either create a stream buffer using file descriptor 1 but on UNIX there is no need anyway because the \n doesn't get replaced in the first place). In particular, reopening the stream to fit in with output redirection is probably not possible.

Can't write to file in a loop containing sleep()

The essence of my problem is that I can't write to a file in a loop with sleep(). If I have the following code:
ofstream file
file.open("file.name");
for(;;) {
file << "HELLO\n";
}
This code works perfectly and prints HELLO repeatedly into "file.name". However, I want to do something like this (I'm recording data from a real-time application):
for(;;) {
file << "HELLO\n";
sleep(1);
}
This doesn't seem to print anything into my file. Any ideas?
You need to flush the output. The output stream is buffering your data into memory but not writing it out to disk. You should either use std::endl (which prints a newline and flushes) instead of the string literal '\n', or explicitly flush the stream with std::flush:
for(;;) {
file << "HELLO" << endl;
}
// or
for(;;) {
file << "HELLO\n" << flush;
}
The magic word you are looking for is "flush".
c++ std::ofstream flush() but not close()
before the sleep, flush the file so that it isn't pending in a buffer waiting for there to be enough of a change to bother writing out.
It's probably just a buffering issue. Because you are now writing much slower, the output buffer wont fill up so fast so you may not 'see' the written data. Try adding a flush() before the sleep.
file.flush()

C/C++ add input to stdin from the program?

Is that even possible ?
Lets say that the code has a lot of scanf lines. Instead of manually running and adding values by hand when debugging, is it possible to "feed" stdin with data so that when the scanf starts reading, it will read the inputted data without any need to interact with the terminal.
Put the test lines into a file, and run the program like this:
myprogram < mytestlines.txt
Better than hacking your program to somehow do that itself.
When you're debugging the code, you can set up the debugger to run it with that command line.
To make your program a little more versatile, you might want to consider rewriting your program to use fscanf, fprintf, etc. so that it can already handle file IO as opposed to just console IO; then when you want to read from stdin or write to stdout, you would just do something along the lines of:
FILE *infile, *outfile;
if (use_console) {
infile = stdin;
outfile = stdout;
} else {
infile = fopen("intest.txt", "r");
outfile = fopen("output.txt", "w");
}
fscanf(infile, "%d", &x);
fprintf(outfile, "2*x is %d", 2*x);
Because how often do programs only handle stdin/stdout and not allow files? Especially if you end up using your program in shell scripts, it can be more explicit to specify input and outputs on the command line.
int fd[2];
pipe(fd);
close(0); // 0:stdin
dup(fd[0], 0); // make read pipe be stdin
close(fd[0]);
fd[0] = 0;
write(fd[1], "some text", 9); // write "some text" to stdin