I need to write all my program output to a text file. I believe it's done this way,
sOutFile << stdout;
where sOutFile is the ofstream object that creates the file like this:
sOutFile("CreateAFile.txt" ); // CreateAFile.txt is created.
When I insert the stdout into the sOutFile object, I get some code which seems to resemble octal [hexadecimal] code or an address of some kind in the text file that I created.
0x77c5fca0
But what's confusing to me is that in my program I use cout several times. Mostly just literal statement. If I'm not mistaken that is the program output.
If this code is an address, would it contain all of my output? Could I read it back in to the program and find out that way?
What can I do to get ALL of my program output written to a text file?
If your program already uses cout/printf and you want to send EVERYTHING you currently output to a file, you could simply redirect stdout to point to a file before your existing calls:
http://support.microsoft.com/kb/58667
Relevant Code:
freopen( "file.txt", "w", stdout );
cout << "hello file world\n"; // goes to file.txt
freopen("CON", "w", stdout);
printf("Hello again, console\n"); // redirected back to the console
Alternatively if you just want Some things to be printed to a file, you just want a regular file output stream: http://www.cplusplus.com/doc/tutorial/files.html
Relevant Code:
ofstream myfile;
myfile.open("file.txt");
myfile << "Hello file world.\n";
printf("Hello console.\n");
myfile.close();
EDIT to aggregate answers from John T and Brian Bondy:
Finally, if you're running it from the commandline, you can just redirect the output as everyone else mentioned by using the redirect operator ">" or append ">>":
myProg > stdout.txt 2> stderr.txt
This is a duplicate of: this question
You can redirect stdout, stderr and stdin using std::freopen.
From the above link:
/* freopen example: redirecting stdout */
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}
You can also run your program via command prompt like so:
a.exe > stdout.txt 2> stderr.txt
If you want all output in a text file you don't need to code anything extra.
from the command line:
program > output.txt
If you only wish to redirect certain output you can use ostream as dirkgently suggested.
Then you cannot use std::cout anywhere else to print stuff from your program. Change std::cout to a std::ostream and then pass your file or std::cout as required.
sOutFile << stdout;
in C "stdout" is defined as a FILE* variable. It's just a pointer. Outputing it to a file just writes the value of the pointer, in your case: 0x77c5fca0 to the file.
If you want to direct your output to a file either write it the a file in the first place or redirect the output of your program to a file using the command line.
Related
I am using llvm::MemoryBuffer::getFileOrSTDIN("-") and, according to the specification, it should Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Now, in the following context:
auto Source = llvm::MemoryBuffer::getFileOrSTDIN(File);
if (std::error_code err = Source.getError()) {
llvm::errs() << err.message();
} else{
someFunction(std::move(*Source), File, makeOutputWriter(Format, llvm::outs()),
IdentifiersOnly, DumpAST);
}
it blocks on the first line (when File == "-"); as expected as the STDIN never closes.
When a special *char appears in STDIN, let's say <END_CHAR>, I know that I am finished reading for a given task. How could I close the STDIN in this situations and move on to someFunction ?
Thanks,
You can always close the stdin file descriptor using close, i.e. close(0). If you check llvm::MemoryBuffer's source, you'll see that getFileOrSTDIN() basically boils down to a call to llvm::MemoryBuffer::getMemoryBufferForStream() with the first argument (the file descriptor) set to 0.
Also, see this SO answer.
The special character to close the standard input is ctrl-d (in *nix at least) on the command line (have a look here).
I want to redirect all stderr to a file, which is also being used by my logger for the entire time the application (game) is running.
The following redirects it away from the console, but it never appears in my file, and using fclose after the game loop is over doesn't actually do anything, where it normally should.
freopen(Logger::logFile.c_str(),"a",stderr);
Any help would be great on how to get stderr to output to the text file, in a game loop.
We might here be playing with undefined behavior... because you must not use freopen to redirect various things to the same file.
In the below example, depending on what file you close, you will write differently:
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf (" This sentence is redirected to a file.");
// fclose (stdout);
freopen ("myfile.txt","w",stderr);
fprintf (stderr, "This ERRORis redirected to a file.");
//fclose (stderr);
fclose (stdout);
return 0;
}
Here you write the error before the sentence:
This ERRORis redirected to a file.sentence is redirected to a file.
Not great. I suggest you let the OS do this redirection to same file work for you, e.g. in Unix / Linux:
./myprog.sh 2>&1
C++ about stdio.h changing stdout
I have a function which prints out some data.
//overallSummary is a void return type function that prints data out to the console. It's works as expected.
I wanted to save to a text file, so this is I did instead
#include <stdio.h>
freopen("summary.txt","w",stdout);
overallSummary();
fclose(stdout);
I ran the code, and it worked as expected.
However, the console kept blinking. It looked like it was blocked. Pressing enter didn't stop it. It wasn't hanging. I just lost the control of the console. Why?
I recommend changing to a more expressive:
#include <iostream>
void overallSummary(std::ostream& os); // use os instead of std::cout in overallSummary
std::ofstream ofs;
ofs.open("summary.txt");
if(!ofs.is_open())
abort();
overallSummary(ofs);
ofs.close();
Otherwise if you just wanna write to a file, that means redirecting std::cout,
so call it like this:
./program_name > summary.txt
In the program writing on std::cout goes into summary.txt. Using ">>" instead of ">" appends.
I know that the function:
system("myfile.sh")
exec a bash script.
Ok but now I want to redirect the output to my program to ensure the reading.
For example the script date.sh give me the date of my system, and i want to see it on my program with std::cout << OUTPUTDATE;
Is it possible?
How?
Use popen instead of system.
The function popen will give you a FILE * you can read from.
FILE *script = popen("myfile.sh", "r");
while (fgets(line, LENGTH, script)) {
/* ... */
}
pclose(script);
My program reads a list of integers from user input [ keyboard] and calculates some statistics
The user enters 'x' to terminate the input process.
So for example,
Enter integers separated by space ( enter x to quit) : 1 2 3 4 5 x
But now I want to include the inputs to be read from file redirection also. So if the numbers followed by x is in a data file, the program should take it from there if not then prompt the user
use isatty for your file descriptor
(0 for standard input)
example:
#include <unistd.h>
main(){
if(isatty(0))
puts("tty"); // print some prompt
else
puts("pipe"); // not really needed in your case
}
You can read strings from a file with fstream and iostream.
Then from there you just parse the strings to see if they contain the correct data. If not, prompt the user for input?
If what you mean is that you can either call your program with a file as a command line argument, or not, in which case you want it to read from standard input, you can do something like this:
#include <fstream>
#include <iostream>
void run(std::istream& in) {
// read all input from 'in' and run your program as normal
}
int main(int argc, char **argv) {
if(argc == 1) {
run(std::cin);
} else if(argc == 2) {
std::ifstream fin(argv[1]);
run(fin);
}
return 0;
}
This way, if you call
./prog
it'll read from standard input (i.e., the keyboard), and if you call
./prog foo.txt
it'll read from the file foo.txt.
You may want to do a little more work when checking the command line arguments, but this is the basic idea.
one approach that would not require any program alterations is to let the shell do the redirection for you.
On both Windows and Unix shells, < redirects a file to stdin for the program.
So, on unix/linux/mac on a console:
./app < file.txt
or windows, at the command prompt, just:
app < file.txt
will take the contents of file.txt and send it as stdin to the program called 'app'.
On a unix box the following should work:
progream <file
where program is your program and file contain the input that the user would type in.