我需要将所有程序输出写入文本文件.我相信它是这样做的,
sOutFile << stdout;
Run Code Online (Sandbox Code Playgroud)
其中sOutFile是创建文件的ofstream对象,如下所示:
sOutFile("CreateAFile.txt" ); // CreateAFile.txt is created.
Run Code Online (Sandbox Code Playgroud)
当我将stdout插入sOutFile对象时,我得到一些似乎相似的代码 八进制 [十六进制]代码或我创建的文本文件中的某种地址.
0x77c5fca0
Run Code Online (Sandbox Code Playgroud)
但令我困惑的是,在我的程序中,我多次使用cout.主要是文字陈述.如果我没弄错那就是程序输出.
如果此代码是地址,它是否包含我的所有输出?我可以把它读回到程序中并找到那个方法吗?
如何将我的所有程序输出写入文本文件?
And*_*son 15
如果您的程序已经使用cout/printf并且您想要将当前输出的所有内容发送到文件,则只需将stdout重定向到指向现有调用之前的文件:http: //support.microsoft.com/kb/58667
相关守则:
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
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想将某些内容打印到文件中,您只需要一个常规的文件输出流:http://www.cplusplus.com/doc/tutorial/files.html
相关守则:
ofstream myfile;
myfile.open("file.txt");
myfile << "Hello file world.\n";
printf("Hello console.\n");
myfile.close();
Run Code Online (Sandbox Code Playgroud)
编辑聚合来自John T和Brian Bondy的答案:
最后,如果您从命令行运行它,您可以通过使用重定向运算符">"或附加">>"重定向输出,如同其他所有人一样:
myProg > stdout.txt 2> stderr.txt
Run Code Online (Sandbox Code Playgroud)
这是一个重复:这个问题
您可以使用重定向stdout,stderr和stdin std::freopen.
从以上链接:
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
您也可以通过命令提示符运行程序,如下所示:
a.exe > stdout.txt 2> stderr.txt
Run Code Online (Sandbox Code Playgroud)
如果您想要文本文件中的所有输出,则无需编写任何额外的代码.
从命令行:
program > output.txt
Run Code Online (Sandbox Code Playgroud)
如果您只想重定向某些输出,可以使用ostream作为Dirkgently建议.