开发者

C++ FILE pointer to stdout?

I'm writing a program and I want the user to be able to specify whether the output is written to a file or to stdout. Until this point, my program has been using printf commands, so I was hoping to simply change the commands to fprintf commands, but my compiler is shouting at me because obviously, they are not the same object clas开发者_高级运维ses.

For example:

FILE *fp;
bool print_to_file;
.
.
.
if(print_to_file){
  fp = fopen("something.txt", "w");
}
else{
  fp = &stdout;
}
fprintf(fp,"%s\t%s\t%s\n",string1 . c_str(), string2 . c_str(), string3 . c_str());

I'd prefer to stick with fprintf and find a FILE pointer to stdout, does anyone know if that's possible? If the answer is no, can I open my files as fstreams, and then use fprintf?


stdout is a FILE*, so you can simply use:

FILE* fp = stdout;


Just drop the ampersand: fp = stdout;.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜