使用freopen()打印到文件和屏幕

Using freopen() to print to file and screen

本文关键字:文件 屏幕 打印 freopen 使用      更新时间:2023-10-16

我正在尝试使用freopen()打印到文本文件和屏幕上,但是我只能将打印成就文件。

我想知道是否有容易将程序输出到文件并将其打印到屏幕上的容易?因为我以这种方式工作,但是我最终不得不两次打印出每个陈述。一个是文件,另一个仅用于输出。

注意:我是C 的新手,我正在尝试下一个学期的课程,因此需要直接答案,因为我已经在网上查看并且找不到任何简单的答案,除了此解决方案之外。

这是我到目前为止所拥有的:

#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<fstream>
using namespace std; 
void menu(){
    cout << "t********************************************************n"
         << "t* Welcome to slot machine.                             *n"
         << "t* Would you like to play? (1 to play, 2 not to play)   *n"
         << "t********************************************************nn";
    return;
}
void update(int arr[], int &token) {
    if (arr[0]==arr[1] && arr[1]==arr[2]) {
        token+=4;
        cout << "You winnn";
    } else if (arr[0]==arr[1] || arr[1]==arr[2] || arr[0]==arr[2]) {
        token+=1;
        cout << "You got two out of threenn";
    } else {
        token-=1;
        cout << "You losenn";
    }
}
int main() {
    freopen("file.txt", "w", stdout);
    int x, arr[3], token=4;
    srand(time(0));
    menu();
    cin >> x;
    while(token!=0) {
        cout << "You have " << token << " tokensnn"
             << "Pull? (1 to pull, 2 not to pull)nn";
        cin>>x;
        if(x==1) {
            for(int i=0; i<3; i++) {
                arr[i]=1+rand()%10;
            }
            cout << "tt";
            for(int j=0; j<3; j++) {
                cout << arr[j] << " ";
            }
            cout << "nn";
            update(arr,token);
        }
        else{  
            cout << "OKn";
        }
    }
    cin.get();
    return 0;
}

我不知道实现这一目标的简单方法,但是我设法以某种方式解决了这个问题。

使用fstreams您可以输出以写入控制台的方式。

#include <fstream>
int main()
{
     std::ofstream f("file.txt");
     f << "something";
}

现在我们可以开始一点:有没有办法可以同时输出到控制台并文件?

我最近写了流媒体的流媒体来解决这个问题:

#include <vector>
#include <ostream>
class stream_demultiplexer
{
private:
    typedef std::vector<std::ostream*> str_cont;
    str_cont d;
public:
    stream_demultiplexer& put(std::ostream::char_type ch)
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (*it)->put(ch);
        return *this;
    }
    stream_demultiplexer& write(const std::ostream::char_type* s, std::streamsize count)
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (*it)->write(s, count);
        return *this;
    }
    stream_demultiplexer& flush()
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (*it)->flush();
        return *this;
    }

    template<typename T>
    stream_demultiplexer& operator<<( const T& obj )
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (**it) << obj;
        return *this;
    }
    stream_demultiplexer& operator<<(std::ios_base& (*func)(std::ios_base&))
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (**it) << func;
        return *this;
    }
    template<typename CharT, typename Traits>
    stream_demultiplexer& operator<<(std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) )
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (**it) << func;
        return *this;
    }
    stream_demultiplexer& operator<<(std::ostream& (*func)(std::ostream&) )
    {
        for(str_cont::iterator it = d.begin(); it != d.end(); ++it)
            (**it) << func;
        return *this;
    }
    void add_stream(std::ostream& ss)
    {
        d.push_back(&ss);
    }
};

您可以这样使用:

stream_demultiplexer spl;
std::ofstream f("file.txt");
spl.add_stream(f);
spl.add_stream(std::cout);
spl << 55 << " HELLO WORLD";

我的方法具有好处,即操作器和未形式的输出正常工作:

spl << 76 << " " << std::hex << 76 << std::endl;
spl.put('a');
spl.write("ABCDE", 5);

unix样环境中的简单方法是使用shell命令 tee

$ my-program | tee output.txt

将把stdout复制到终端,也将将 output.txt


如果您必须在代码中进行操作,则可以使用自己的输出流,而不是cout,该流将每个operator<<转发到两个(或更多)ostreams。这比在C ostream cout的C输出文件中烦恼的情况更好(对我来说)。

#include <ostream>
class Tee {
    std::ostream &first, &second;
    template<typename T> friend Tee& operator<< (Tee&, T);
public:
    Tee(std::ostream &f, std::ostream &s) : first(f), second(s) {}
};
template <typename T>
Tee& operator<< (Tee &t, T val)
{
    t.first << val;
    t.second << val;
    return t;
}

然后,如果您用以下方式替换了Freopen Line。

std::ofstream outfile("file.txt");
Tee tee(std::cout, outfile);

您只能使用tee <<而不是cout <<

请注意,您要么需要将tee传递到您的功能中,要么使其成为全球性工作。