using > instead of stdout - c++

So for my program I need to take all the informations that are shown in cmd.exe and put them on a file.
So for that I used the following code
freopen ("text.txt","w",stdout);
and I had to put it in the main.cpp
However I was told that I should do that in a diffrent class and that I could use the > symbol directly.
Could you guys tell me how I can do that?
If you could give me an example that would be great.

I think you were told about pipes. In you shell, you can type something like:
somecommand > text.txt
And it will write the output of somecommand into text.txt.

std::cout << "Output sentence"; // prints Output sentence on screen
std::cout << 120; // prints number 120 on screen
std::cout << x; // prints the content of x on screen
If you use those then the user can redirect your output (which will normally go to the console) to a file instead by using the syntax below.
yourapplication.exe > "output.txt"
If you use std::cin with the << operator then you can also < "input.txt" to enter text from input.txt as if the user typed it.
http://www.cplusplus.com/doc/tutorial/basic_io/ explain the input and output streams fairly well.
http://technet.microsoft.com/en-us/library/bb490982.aspx explains console redirection.

Related

How detect a input injected from bash in a background process using std::in and getline()

I have a binary compiled in Cpp with the following code:
std::string input;
getline(std::cin, input);
std::cout << "Message given: " << input << std::endl;
If I execute this example, and write in the terminal "Hello world!" works perfectly:
Message given: Hello world!
Now, I launch the executable in redirecting stdout:
./basicsample >> output/test
If I try to inject inputs using file descriptor:
echo "Hello world!" > /proc/${PID}/fd/0
The message appear in terminal that launched the process:
[vgonisanz#foovar bash]$ ./basicsample >> output/test
Hello world!
But the message no appear in the programs output. I expect to get the message processed by getline, and it is not detected! But, If I write directly in that bash, the program get the input. I'm trying to do a script to inject inputs in a background process but it is not working.
How could I inject inputs to be detected into the process without do it manually?
UPDATE:
It seems that using expect, this could work, but I will prefer to avoid dependencies like this. After several tries, the best way to do it without dependencies is to use a pipe, in example:
mkdir tmp; mkfifo tmp/input.pipe; nohup ./basicsample tmp/user.out 2> tmp/nohup.err
This will run the creating a input pipe, an output for console and error.
Then, just feed the pipe using:
echo "Hello world!" > tmp/input.pipe
The problem of this is, the pipe works only once. After getting an input, it won't never listen it again. Maybe this is the way but I don't know how to avoid to lost the focus.
I tried to redirect it using several ways like files, etc, but it doesn't works. Thanks in advance.
The best way to do it without dependencies is to use a pipe, in example:
mkdir tmp
mkfifo tmp/input.pipe
(tail -f tmp/input.pipe) | ./basicsample > tmp/log.0 &
This will run creating an input pipe and an output saved in log file. You can prevent console blocking using the operator & to launch it in background.
Then inject data using:
echo "YOUR_STRING" > tmp/input.pipe
It should work for your posed problem.

C++, Print to screen even with > file.out in command line

I am manipulating characters from a file and sending them to another file using command line (which I am pretty new to).
a.out -d 5 < garbage01.txt > garbage02.txt
The characters are going to garbage02.txt through cout.put(char). If the command line arguments don't validate I just want to print to screen a simple message to state that, but everything goes to garbage02.txt. Changing the layout of the command is not an option.
I hope this is a pretty straight-forward issue, that I am just having difficulty finding a solution to.
It is common to write error messages to stderr and normal output to stdout. To print an error message to stderr do
std::cerr << "Something went wrong\n";
(You can also do this with fprintf, but that is usually not needed.)
Output written to stderr will not be redirected by
> someFile
but only by
2> someFile
so the user can choose where they want to see the "normal" and the "error" output separately.
std::cerr also has the nice property that it does not buffer the output (unlike std::cout). That means that the user will see the error message before the program continues after the output line.
If you do not want this non-buffer functionality, use std::clog.
You can use /dev/tty file for that, it is a special file representing terminal for current process.
#include <fstream>
std::ofstream screen("/dev/tty");
screen<<"Your message"<<std::endl;
Either use std::cerr to print to screen
std::cerr << "Some message" << std::endl;
or change your terminal command
a.out -d 5 < garbage01.txt 2> garbage02.txt # Redirect stderr stream only

New to C++, I do not understand how to display output in a .txt file

I am very new to C++. I have my code and it displays my desired output in a win32 console.
However, my Instructor wants the output to be run through a .txt file. We have done this before with a program that had input already written within the coding.
ex.
cout << "example1....example2";
We achieved this with his exact instructions:
*1) Probably the easiest way to obtain a hard copy of the generated
program output on a Microsoft Windows platform is to run your
program from a command prompt, redirecting the output to a file.
The command line syntax would like like this:
lab1prog >lab1.txt*
My problem, however, is that I did this again for lab2 and redirected the output to lab2.txt but I need user input for this time around. When I run the lab2.exe file, my lab2.txt file outputs my "cout" statement and waits for input but I cannot enter input through a .txt file.
Please help if you can.
When you redirect the output of the program with
lab1prog >lab1.txt
then the user is still able to input data. The only problem is that she doesn't know when to enter what data. This is usually done by prompt outputs that are hidden whith the >lab1.txt.
To circumvent the problem you could abuse the error output what is not redirected with the command above.
cerr << "prompt";
To avoid this abuse you should use a "tee" program like wintee instead of redirecting with a simple >lab1.txt.
If it's acceptable to get the input from a file instead from the user you can use the input redirection.
labprog1 <input.txt >lab1.txt
If you specifically want to use a text file as input into your program, the easiest way (as Kamil Mikolajczyk mentioned) is to run it this way:
> lab1prog >lab1.txt <input.txt
On the other hand, if you need to run the program as it is, but have complete control over what to output into the file, I'd suggest using a file handle. Check out this question on how to use file handles. You could even duplicate the output on the command prompt and the file when you want by outputting it as:
fout << "My output";
cout << "My output";
You can as well output the user input into your output file for your convenience.

C++ Reading from keyboard after giving a .txt to program (used getline() after in)

Ok here's the problem and I'm despaired about it.
I get a 9*9 table using
for (int i=0 ; i < 9 ; i++)
for (int j=0 ; j < 9 ; j++)
cin >> table [i][j];
I want to make some changes to this table . so I get a
command using:
getline (cin , command);
so user would type a command and after parsing it I will make the changes to the table. (it has to be getline() because command is an string and contains spaces)
I have an in.txt containing the table . I give this file to my code using :
g++ main.cpp
./a.out < in.txt .
(these two commands are written in terminal)
after that I want to give my command using keyboard . but the getline() doesn't get anything from keyboard . I tried using
cin.ignore() , cin.clear() , cin.sync () , even cin.get()
but it always passes the getline() .
Any suggestions would be appreciated .
thanks in advance.
Well this is obvious why any input from standard input won't work. This is not limited to getline. operator>> also won't work, nor anything associated with std.cin or stdin.
This is because ./a.out < in.txt is not "giving a txt to a program". It is redirecting the standard input. By default it is a keyboard input from terminal, but you are switching it to a file on a shell level.
If you wanted to switch from terminal associated input to a file, and then backwards, this would be handy: How to redirect cin and cout to files?. Though, in this your case, you will not have the original buffer associated with the terminal, precisely because you make OS not give it to you. You would need to obtain somehow from the system. This would be more complicated (well it would be os specific and less portable) than below suggestions.
I would suggest you to pass the filename as an argument and do not redirect standard input. Or, if you are gonna write some command prompt anyways, make a load_file command, for loading the file. Then load the file using regular means designed for files e.g. ifstream.

Is it possible to cout to terminal while redirecting cout to outfile?

I'm running a program and redirecting cout to an outfile, like so:
./program < infile.in > outfile.o
I want to be able to read in an option ('-h' or '--help') from the command line and output a help message to the terminal. Is there a way I can do this but still have the regular cout from the rest of the program go to the outfile?
Would cout be the right object to use for such a thing?
You should use cerr to output your help message to STDERR, which is not included in your redirection to outfile.o.
Given ./program < infile.in > outfile.o:
cout << "This writes to STDOUT, and gets redirected to outfile.";
cerr << "This doesn't get redirected, and displays on screen.";
If, later on, you want to redirect both STDOUT and STDERR, you can do
./program < infile.in &> outfile.o
If you want to redirect only STDERR, but allow STDOUT to display, use
./program < infile.in 2> outfile.o
Bash redirection is more complex than most people realize, and often everything except the simplest form (">") gets overlooked.
If you're on linux you can use the pseudo device /dev/tty to output to a controlling terminal (if any). This will work even if stderr is redirected as well as stdout. Other operating systems may provide similar mechanisms.
E.g.
#include <iostream>
#include <ostream>
#include <fstream>
int main()
{
std::ofstream term("/dev/tty", std::ios_base::out);
term << "This goes to terminal\n";
std::cout << "This goes to stdout\n";
return 0;
}
Will work like this:
$ ./a.out
This goes to stdout
This goes to terminal
$ ./a.out >/dev/null
This goes to terminal
Note the way that the with the two streams being buffered independently the relative ordering if they are outputting to the same device is not necessarily preserved. This can be adjusted by flushing the streams at appropriate times.
~$ cmd | tee log_file to dup stdout to file and terminal
~$ cmd 2>log_file to print stdout onto terminal and stderr into a file
You may like to output the help message to stderr. Stderr is generally used for non-normal output and you may consider a usage paragraph to be such output.
One of the things I've done - not saying this is always appropriate - is write modules that have something like this signature.
void write_out(ostream &o);
And then I can create fstream objects and pass them in, or pass in cout and cerr, whatever I need to at that time. This can be helpful in writing logging code where sometimes you want to see on-terminal what happens, and at other times you just want a logfile.
HTH.
You should use cerr instead of cout. Using shell redirection > only redirects stdout (cout), not stderr (cerr).