1
#include <iostream>
#include <fstream>
using namespace std;

void foo(){
  streambuf *psbuf;
  ofstream filestr;
  filestr.open ("test.txt");
  psbuf = filestr.rdbuf(); 
  cout.rdbuf(psbuf);    
}

int main () {
  foo();
  cout << "This is written to the file";
  return 0;
}

cout は指定されたファイルに書き込みますか?

そうでない場合、変数を foo に送信せずにそれを行う方法はありnewますか?


更新:

クラスまたはグローバルを使用するソリューションを使用できないため、new を使用するソリューションを教えてください。また、main から foo に渡します

streambuf *psbuf;
ofstream filestr;

正しく動作するはずですか?

私はこれをやろうとしていますが、うまくいきませんか?ストリームを foo に渡し、メインに存在するようにして、foo が終了しても終了しないようにします。

 void foo(streambuf *psbuf){

  ofstream filestr;
  filestr.open ("test.txt");
  psbuf = filestr.rdbuf(); 
  cout.rdbuf(psbuf);    
}

int main () {
streambuf *psbuf
  foo(psbuf);
  cout << "This is written to the file";
  return 0;
}
4

2 に答える 2

4

コードをコンパイルして実行したところ、セグメンテーション違反が発生したと思われます。

ofstreamこれは、内でオブジェクトを作成して開き、foo()の最後で破棄 (および閉じ) されるためですfoo。でストリームに書き込もうとすると、main()存在しないバッファにアクセスしようとします。

これに対する1 つの回避策は、filestrオブジェクトをグローバルにすることです。もっといいのいっぱいあります!

編集: @MSalters によって提案されたより良い解決策は次のとおりです。

#include <iostream>
#include <fstream>

class scoped_cout_redirector
{
public:
    scoped_cout_redirector(const std::string& filename)
        :backup_(std::cout.rdbuf())
        ,filestr_(filename.c_str())
        ,sbuf_(filestr_.rdbuf())
    {
        std::cout.rdbuf(sbuf_);
    }

    ~scoped_cout_redirector()
    {
        std::cout.rdbuf(backup_);
    }

private:
    scoped_cout_redirector();
    scoped_cout_redirector(const scoped_cout_redirector& copy);
    scoped_cout_redirector& operator =(const scoped_cout_redirector& assign);

    std::streambuf* backup_;
    std::ofstream filestr_;
    std::streambuf* sbuf_;
};


int main()
{
    {
        scoped_cout_redirector file1("file1.txt");
        std::cout << "This is written to the first file." << std::endl;
    }


    std::cout << "This is written to stdout." << std::endl;

    {
        scoped_cout_redirector file2("file2.txt");
        std::cout << "This is written to the second file." << std::endl;
    }

    return 0;
}
于 2010-09-08T11:41:40.247 に答える
1

あなたのコードは動作するはずですが...自分で試してみませんか? すべてがtest.txtに書かれているかどうかがわかります。

于 2010-09-08T11:40:47.500 に答える